im programming a socket application using c# (.net framework) but when i try it on the local system or private network it works well but when i try it on two different system using internet (public network) it never connect
its my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
SocketPermission me = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", SocketPermission.AllPorts);
Socket mes =
new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
Socket des;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
IPHostEntry iphost = Dns.GetHostEntry("");
IPAddress ipaddr = iphost.AddressList[0];
MessageBox.Show(ipaddr.ToString());
IPEndPoint iep = new IPEndPoint(ipaddr, 44444);
label1.Text = ipaddr.ToString();
mes.Bind(iep);
mes.Listen(4);
des = mes.Accept();
MessageBox.Show("connected");
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
IPHostEntry iphost = Dns.GetHostEntry("");
IPAddress ipaddr = iphost.AddressList[0];
MessageBox.Show(ipaddr.ToString());
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(textBox1.Text), 44444);
mes.Connect(iep);
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
}
}
textbox1 return server ipv6.
im using socket permission to open all ports for tcp .
and ipv6 because its unique .
Related
I managed to create a client server that communicate through forms.
I am able to display fist waiting and accepted messages.
My problem is when I'm writing to the stream and reading it on the other side the forms.
Here is where the sending and receiving happens on both programs:
Server-side code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
using System.Diagnostics;
namespace serverApp
{
public partial class Form1 : Form
{
private static int connections = 0;
public Form1() { }
private void Form1_Load(object sender, EventArgs e)
{
}
private void CreateServer()
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 9050);
server.Bind(localEP);
server.Listen(10);
serverTxtbox.AppendText("waiting for a client");
BackgroundWorker worker1 = new BackgroundWorker();
worker1.RunWorkerAsync(handlingFunction(server));
}
public object handlingFunction(Socket server)
{
while (true)
{
try
{
Socket client = server.Accept();
NetworkStream ns = new NetworkStream(client);
StreamReader reader = new StreamReader(ns);
StreamWriter writer = new StreamWriter(ns);
connections++;
serverTxtbox.AppendText("New client accepted: active connections
${connections}");
writer.WriteLine("Welcome to my server");
writer.Flush();
string input;
while (true)
{
input = reader.ReadLine();
if (input.Length == 0 || input.ToLower() == "exit")
break;
serverTxtbox.AppendText(input);
writer.WriteLine(input);
writer.Flush();
} //end of while
ns.Close();
//client.Close();
//connections--;
Console.WriteLine("Client disconnected: {0} active connections",
connections);
}
catch (Exception)
{
connections--;
Console.WriteLine("Client disconnected: {0} active connections", connections);
} //end of catch block
} // end of HandleConnection function
private void serverTxtbox_TextChanged(object sender, EventArgs e)
{
serverTxtbox.Clear();
}
private void button1_Click(object sender, EventArgs e)
{
//start button
try
{
CreateServer();
}
catch (Exception)
{
serverTxtbox.AppendText("Connection failed ..");
}
//client.Close();
//server.Shutdown();
}
}
}
Client-side code:
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
namespace app
{
public partial class Form1 : Form
{
Socket client;
NetworkStream stream;
StreamReader reader;
StreamWriter writer;
public Form1()
{
InitializeComponent();
}
private void sendBtn_Click(object sender, EventArgs e)
{
// writing to the server
handlfun();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private object ConnectionToServer(Socket client, IPEndPoint remoteEP)
{
//client.Connect(remoteEP);
try
{
client.Connect(remoteEP);
clientTextbox.Text = "Enter Message for Server <Enter to Stop >: ";
}
catch (SocketException e)
{
clientTextbox.AppendText("Unable to connect to server. ");
// clientTextbox.AppendText("e");
}
return client;
// Client.Shutdown(SocketShutdown.Both);
// Client.Close();
}
private void connectbtn_Click(object sender, EventArgs e)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
BackgroundWorker worker1 = new BackgroundWorker();
worker1.RunWorkerAsync(ConnectionToServer(client, remoteEP));
}
public void handlfun()
{
stream = new NetworkStream(client);
reader = new StreamReader(stream);
writer = new StreamWriter(stream);
String input = clientTextbox.Text;
writer.WriteLine(input);
//clientTextbox.Text = input;
// String input = reader.ReadLine();
writer.Flush();
String line = null;
while (true)
{
clientTextbox.Text = "Enter Message for Server <Enter to Stop >: ";
line = clientTextbox.Text;
writer.WriteLine(line);
writer.Flush();
if (line.Length != 0)
{
line = "Echo: " + reader.ReadLine();
clientTextbox.Text = line;
}
}
}
}
}
i have a simple TCP/IP client and server that does not work:
i want to use it to transfer data between some clients and a server
enter image description here
enter image description here
on server side i have:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections;
namespace TCP_IP_Server
{
public partial class frmMain : Form
{
private ArrayList nSockets;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
IPHostEntry IPhost = Dns.GetHostByName(Dns.GetHostName());
lblStatus.Text = "IP Address: " + IPhost.AddressList[0].ToString();
nSockets = new ArrayList();
Thread thdListner = new Thread(new ThreadStart(listnerThread));
}
public void listnerThread()
{
TcpListener tcpListener = new TcpListener(8080);
tcpListener.Start();
while(true)
{
Socket handlerSocket = tcpListener.AcceptSocket();
if(handlerSocket.Connected)
{
Control.CheckForIllegalCrossThreadCalls = false;
lbConnections.Items.Add(handlerSocket.RemoteEndPoint.ToString() + " Connected.");
lock (this)
{
nSockets.Add(handlerSocket);
}
ThreadStart thdstHandler = new ThreadStart(handlerThread);
Thread thdHnadler = new Thread(thdstHandler);
thdHnadler.Start();
}
}
}
public void handlerThread()
{
Socket handlerSocket = (Socket)nSockets[nSockets.Count - 1];
NetworkStream networkStream = new NetworkStream(handlerSocket);
int thisRead = 0;
int BlockSize = 1024;
byte[] dataByte = new byte[BlockSize];
lock (this)
{
Stream fileStream = File.OpenWrite(#"%userprofile%\desktop\SubmitedFile.txt");
while(true)
{
thisRead = networkStream.Read(dataByte, 0, BlockSize);
fileStream.Write(dataByte, 0, thisRead);
if (thisRead == 0)
break;
}
fileStream.Close();
}
lbConnections.Items.Add("File Written.");
handlerSocket = null;
}
}
}
and on Clinet side:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace TCP_IP_Client
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
ofdBrowse.ShowDialog();
txtFile.Text = ofdBrowse.FileName;
}
private void btnSend_Click(object sender, EventArgs e)
{
Stream fileStream = File.OpenRead(txtFile.Text);
byte[] fileBuffer = new byte[fileStream.Length];
fileStream.Read(fileBuffer, 0, (int)fileStream.Length);
TcpClient tcp = new TcpClient(txtServer.Text, 8080);
NetworkStream networkStream = tcp.GetStream();
networkStream.Write(fileBuffer, 0, fileBuffer.GetLength(0));
networkStream.Close();
}
}
}
i am running the server on a VPS that hase statick IP adress and the client on my own pc, but after hiting send button an exception occures:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond **.**.**.**:8080
1. Programmatic Issue
Don't forget to start the thread after creating
private void frmMain_Load(object sender, EventArgs e)
{
IPHostEntry IPhost = Dns.GetHostByName(Dns.GetHostName());
lblStatus.Text = "IP Address: " + IPhost.AddressList[0].ToString();
nSockets = new ArrayList();
Thread thdListner = new Thread(new ThreadStart(listnerThread));
thdListner.start();
}
2. Network Issue
Take the IP-address used by the code to host the server and Ping the address on the client.
If succeeded, check the firewall settings of the server, client (may temporarly switch of the firewall to check if this is the problem)
If you're using dns names execute an nslookup on the client
I'm working on creating a UDP socket to send and receive data through the PC and a radio terminal device connected to the PC. I can successfully send the data that I want to send, but when it comes to receiving data sent from the radio device to the PC nothing happens the code just stops at the " Byte[] receiveBytes = receivingUdpClient.Receive(ref ipep); " in the Receive function and nothing happens afterwords. The radio device has an IP address = 192.168.1.191 and Port number = 50000. I've also tried to receive through " Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint); " but still nothing the code also stops at this point and nothing happens afterwords. Below is the complete code that I have. Any help would be very appreciated, thanks in advance.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace UDP_Socket
{
public partial class Form1 : Form
{
#region Importand Definitions
public UdpClient udpClient;
public String IPaddress;
public String PortNumber;
public IPEndPoint ipep;
#endregion
private void Form1_Load(object sender, EventArgs e)
{
Connect();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (udpClient.Client.Connected == true)
{
udpClient.Client.Close();
udpClient.Client.Dispose();
}
}
private void Add_Btn_Click(object sender, EventArgs e)
{
RadioCheck();
Receive();
}
void RadioCheck()
{
byte[] data = Encoding.ASCII.GetBytes("at");
udpClient.Send(data , data .Length);
}
void Connect()
{
IPaddress = "192.168.1.191";
PortNumber = "50000";
//Uses a remote endpoint to establish a socket connection.
udpClient = new UdpClient();
IPAddress ipAddress = IPAddress.Parse(IPaddress);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, Convert.ToInt32(PortNumber));
ipep = ipEndPoint;
try
{
udpClient.Connect(ipEndPoint);
MessageBox.Show("Successfully connected to: " + ipep.ToString(), "Connection", MessageBoxButtons.OK);
}
catch (SocketException ex)
{
Console.WriteLine(ex.ToString());
MessageBox.Show("Problem connecting to: " + ipep.ToString(), "Connection", MessageBoxButtons.OK);
}
}
void Receive()
{
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient(50000);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
Byte[] receiveBytes = receivingUdpClient.Receive(ref ipep);//RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
ipep.Address.ToString() +
" on their port number " +
ipep.Port.ToString()); //RemoteIpEndPoint
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
I'm writing a program that can manage computers in a network environment.
I try to be a part of this program will assign the control of the remote client(Remote Desktop) . but my target is like teamviewer not RDC(RDP) .
i want make a service and put it into Client , that Service running every time (Automatic , Auto Start)
I use sending mouse and keyboard from server to client and screenshot of desktop of client will be transfer to server, the destination computer must control.
i write it by BackgroundWorker in loop ( in Complete_BW i put BW.RunWorkerAsync() )
i use socket and when i run program my server rise error after 1 or 2 times sent desktop image to server , error is in Socket.EndPoint ...
codes is here :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.IO;
namespace remServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
bw.RunWorkerAsync();
}
public Image GetImage(byte[] byteArrayIn)
{
Image ret = null;
try
{
MemoryStream ms = new MemoryStream(byteArrayIn);
ret = Image.FromStream(ms);
}
catch { }
return ret;
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
FTServerCode f = new FTServerCode();
Byte[] getCap = f.StartServer();
img.Image = GetImage(getCap);
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
bw.RunWorkerAsync();
}
}
public class FTServerCode
{
IPEndPoint ipEnd;
Socket sock;
public FTServerCode()
{
try
{
ipEnd = new IPEndPoint(IPAddress.Any, 5656); // Error In this Line
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
}
catch { }
}
public Byte[] StartServer()
{
byte[] clientData = new byte[1024 * 5000];
try
{
sock.Listen(100);
Socket clientSock = sock.Accept();
int receivedBytesLen = clientSock.Receive(clientData);
clientSock.Close();
}
catch (Exception ex)
{
MessageBox.Show("File Receving error." + ex.Message);
}
return clientData;
}
}
}
if client code is Necessary tell me to put in here . tnx
When I run the program I get an invalid IP address error. I'm trying to have it so that users can put an IP address in the textbox and use that to send UDP packets. I don't know what is wrong with the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
namespace ProjectTakedown
{
public partial class Form1 : Form
{
public Form1() //where the IP should be entered
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e) //button to start takedown
{
byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes("<Packet OF Data Here>");
string IP = "URL";
int port = 80;
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.SendTo(packetData, ep);
}
private void Stop_Click(object sender, EventArgs e)
{
}
private void URL_TextChanged(object sender, EventArgs e)
{
}
}
}
Somehow it's not reading the IP address.
Could it be this line perhaps?
string IP = "URL";
Don't you need to be able to dynamically inject the IP Address?
It should probably look something like this...
string IP = txtIPAddress.Text;
IP must be a string in dotted decimal notation (IPv4) or a colon-hex notation (IPv6)
Example:
127.0.0.1
::1