UDP Client server works on same computer but not over lan - c#

I have a simple application that sends continuous UDP packets from a server to a client. Everything works well if the server app and client app are on the same computer but the minute I move the client to another computer in the LAN it stops working with a message
"the requested address is not valid in its context". I really don't understand why this is happening.
Here is the server code:
public void SendData()
{
udpClient = new UdpClient();
for (int i = 0; i < 8192; i++)
{
dataBytes[i] = Convert.ToByte(Convert.ToInt16(dataValues[i]));
}
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
try
{
udpClient.Connect(ipAddress, port);
udpClient.Send(dataBytes, dataBytes.Length);
}
catch (Exception ex)
{
}
}
On the client machine here is the code:
private void receive()
{
try
{
udpClient = new UdpClient();
udpClient.Client.ReceiveTimeout = 1000;
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
int port = Convert.ToInt32("13064");
IPAddress ipAddress = IPAddress.Parse("192.168.1.107");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
socket = new UdpClient(localEndPoint);
udpClient.Connect(ipAddress, port);
socket.BeginReceive(new AsyncCallback(ReceivedDataCallback), socket);
}
catch (Exception ex)
{
if (!socketConnected)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ReceivedDataCallback(IAsyncResult AR)
{
try
{
socketConnected = true;
clientSocket = AR.AsyncState as UdpClient;
var port = Convert.ToInt32("13064");
IPAddress ipAddress = IPAddress.Parse("192.168.1.107");
IPEndPoint source = new IPEndPoint(ipAddress, port);
nums = clientSocket.EndReceive(AR, ref source);
OutputRemoteSamples();
clientSocket.BeginReceive(new AsyncCallback(ReceivedDataCallback), clientSocket);
}
catch (Exception ex)
{
}
}
Thanks for any suggestions
Tom

Related

c# Sockets Programming Errors

Hello im trying to create a connection which connect two pc. In local code the below is working without any trouble but when we starts the clients code in different pc, we cant connect. The code is below. where is the mistake?
the client side:
void Start()
{
Debug.Log(string.Format("Starting TCP and UDP clients on port {0}...", 90));
udpThread = new Thread(new ThreadStart(ClientThread));
udpThread.Start();
}
void ClientThread()
{
try
{
// Establish the remote endpoint
// for the socket. This example
// uses port 11111 on the local
// computer.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
string strHostName = "";
strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress addr = ipEntry.AddressList[0];
IPAddress addr2 = ipEntry.AddressList[1];
IPEndPoint localEndPoint = new IPEndPoint(addr, 90);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket sender = new Socket(addr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(localEndPoint);
Console.WriteLine("Socket connected to -> {0} ",
sender.RemoteEndPoint.ToString());
byte[] messageSent = Encoding.ASCII.GetBytes("Test Client<EOF>");
int byteSent = sender.Send(messageSent);
byte[] messageReceived = new byte[1024];
int byteRecv = sender.Receive(messageReceived);
Console.WriteLine("Message from Server -> {0}",
Encoding.ASCII.GetString(messageReceived,
0, byteRecv));
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
And server side
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine(string.Format("Starting TCP and UDP servers on port {0}...", port));
devices_battery_midlow_pic_1.Visible = false;
devices_battery_low_pic_1.Visible = false;
devices_battery_midhigh_pic_1.Visible = false;
devices_battery_high_pic_1.Visible = false;
play_button.Anchor = (AnchorStyles.Bottom);
Console.WriteLine(DateTime.Now.ToString() + " Getting IP...");
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
connection_id_label.Text = "This IP:\n" + ipAddress.MapToIPv4().ToString();
Console.WriteLine(DateTime.Now.ToString() + " Starting Connection Thread...");
connectionThread = new Thread(new ThreadStart(StartServer));
connectionThread.IsBackground = true;
connectionThread.Start();
}
private void StartServer()
{
string strHostName = "";
strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress addr = ipEntry.AddressList[0];
Console.WriteLine(addr.MapToIPv4().ToString() + " Starting Connection Thread...");
IPEndPoint localEndPoint = new IPEndPoint(addr, 90);
Socket listener = new Socket(addr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
Console.WriteLine("Waiting connection ... ");
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024];
string data = null;
Console.WriteLine("Text received -> {0} ", data);
byte[] message = Encoding.ASCII.GetBytes("Test Server");
clientSocket.Send(message);
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
That is working on one pc, but if we move our server code to other pc, we cant take any response. Where is error??
The client code connects explicitly to a server on the same computer. Instead of calling Dns.GetHostName(), you should use a configurable value like a command line argument or read a configuration file.

C# Socket works locally but not remotely

I have a C# Client and a seperate Server application. When i execute both on the same machine, im able to connect to the server. However, when i try to connect to my server remotely it always ends in a timeout. I use the port 139 and I tried running the server application on mulitple machines. I have tried it on a server that is open to the public, my private PC with my router forwarding this port to the PC, as well as laptops in the same network.
I have always checked if the machine the server is running on is listening on the port using netstat -an and made exceptions in the firewall on all of them.
The code I use on the client to connect to the server:
static IPHostEntry ipHostInfo = Dns.GetHostEntry("xxx.xxx.xxx.xxx");
static IPAddress ipAddress = ipHostInfo.AddressList[0];
static IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
static Socket client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
static private void ConnectToServer()
{
try
{
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
}
catch (Exception ex)
{
Console.WriteLine("Error: ", ex.ToString());
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
The code I use to accept the connection on the server:
static IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
static IPAddress ipAddress = ipHostInfo.AddressList[0];
static IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 139);
static Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
allDone.Reset();
Console.WriteLine("Listening on: " + ipAddress);
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
static void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
As I said this works flawlessly when both client and server application are executed on the same PC. If however they are on different machines the client gets a timout error within a couple of seconds.
Any help is appreciated, Thanks.

Canot create udp connection on mono

I can not create a UDP connection:
public void Connect(String host, int port)
{
System.Net.IPAddress address = Dns.GetHostAddresses (host)[0];
this.hostport = new IPEndPoint(address, port);
this.socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp
);
this.socket.BeginConnect(this.hostport, new AsyncCallback(socket__onConnect), this.socket);
}
private void socket__onConnect(IAsyncResult ar)
{
// It is never called on udp connections :(
try
{
Socket client = (Socket) ar.AsyncState;
client.EndConnect(ar);
Console.WriteLine("Success!");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Try connect but socket__onConnect is never called.
With TCP works fine but UDP doeas not works.
I have perrmissions to connect udp port:
nc -v -u host.com 53
Works fine.
Mono bug? try this:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) { ExclusiveAddressUse = true ; } ;

I am not able to receive my own Mcast packets C# UdpClient

I am not able to receive back my own packets send on multicast. i created two Udpclient receiver is to receive packets on multicast group and sender is to send packets. my packets are send to the group but i cannot receive back the packets send by me....
public void Join()
{
IPAddress ip1 = IPAddress.Any;
localep = new IPEndPoint(ip1, port);
Receiver = new UdpClient();
Receiver.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Receiver.Client.Bind(localep);
Sender = new UdpClient();
Sender.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Sender.Client.Bind(localep);
IPAddress ip = IPAddress.Parse(IP);
remoteep = new IPEndPoint(ip, port);
Sender.JoinMulticastGroup(ip);
Sender.EnableBroadcast = true;
Sender.MulticastLoopback = true;
Receiver.JoinMulticastGroup(ip);
Receiver.EnableBroadcast = true;
Receiver.MulticastLoopback = true;
udpState.ipEndpt = RemoteIpEndPoint;
udpState.udpClient = Receiver;
Receiver.BeginReceive(new AsyncCallback(GetMsg), udpState);
}
void GetMsg(IAsyncResult ar)
{
UdpClient udpClient = (UdpClient)((UdpState)(ar.AsyncState)).udpClient;
IPEndPoint ipEndpt = (IPEndPoint)((UdpState)(ar.AsyncState)).ipEndpt;
RecByte = Receiver.EndReceive(ar, ref ipEndpt);
}
//Sending packets logic
McastOTS.Sender.Send(sendBytes, sendBytes.Length, McastOTS.remoteep);
Seems to me all you need to do is call BeginReceive again after your EndReceive. Otherwise, you'll only get 1 message and won't see any others...
void GetMsg(IAsyncResult ar)
{
UdpClient udpClient = (UdpClient)((UdpState)(ar.AsyncState)).udpClient;
IPEndPoint ipEndpt = (IPEndPoint)((UdpState)(ar.AsyncState)).ipEndpt;
RecByte = Receiver.EndReceive(ar, ref ipEndpt);
Receiver.BeginReceive(GetMsg, udpState);
}

How can I test a TCP connection to a server with C# given the server's IP address and port?

How can I programmatically determine if I have access to a server (TCP) with a given IP address and port using C#?
You could use the Ping class (.NET 2.0 and above)
Ping x = new Ping();
PingReply reply = x.Send(IPAddress.Parse("127.0.0.1"));
if(reply.Status == IPStatus.Success)
Console.WriteLine("Address is accessible");
You might want to use the asynchronous methods in a production system to allow cancelling, etc.
Assuming you mean through a TCP socket:
IPAddress IP;
if(IPAddress.TryParse("127.0.0.1",out IP)){
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
try{
s.Connect(IPs[0], port);
}
catch(Exception ex){
// something went wrong
}
}
For more information: http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4
Declare string address and int port and you are ready to connect through the TcpClient class.
System.Net.Sockets.TcpClient client = new TcpClient();
try
{
client.Connect(address, port);
Console.WriteLine("Connection open, host active");
} catch (SocketException ex)
{
Console.WriteLine("Connection could not be established due to: \n" + ex.Message);
}
finally
{
client.Close();
}
This should do it
bool ssl;
ssl = false;
int maxWaitMillisec;
maxWaitMillisec = 20000;
int port = 555;
success = socket.Connect("Your ip address",port,ssl,maxWaitMillisec);
if (success != true) {
MessageBox.Show(socket.LastErrorText);
return;
}

Categories

Resources