Koorosh Sarfaraz
Koorosh Sarfaraz

Reputation: 71

Concurrent send and receive data in one port with udpclient

I'm trying to send and receive data to a specific endpoint with local port 50177. Send data does very good, but when the program tries to receive data it can't receive any. When I sniff the network with Wireshark I see that server sent data to me. I know that I can't have 2 UdpClient on one port at the same time.

Can any one help me?

UdpClient udpClient2 = new UdpClient(50177);
IPEndPoint Ip2 = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1005);
udpClient2.Send(peerto255, peerto255.Length, Ip2);

IPEndPoint Ip = new IPEndPoint(IPAddress.Parse("10.10.240.1"), 1005); 
var dgram = udpClient2.Receive(ref Ip);

Upvotes: 7

Views: 15498

Answers (2)

Farzan
Farzan

Reputation: 935

You can absolutely have two UdpClient on one port but you need to set socket options before you bind it to an endpoint.

private static void SendAndReceive()
{
  IPEndPoint ep1 = new IPEndPoint(IPAddress.Any, 1234);
  ThreadPool.QueueUserWorkItem(delegate
  {
    UdpClient receiveClient = new UdpClient();
    receiveClient.ExclusiveAddressUse = false;
    receiveClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    receiveClient.Client.Bind(ep1);
    byte[] buffer = receiveClient.Receive(ref ep1);
  });

  UdpClient sendClient = new UdpClient();
  sendClient.ExclusiveAddressUse = false;
  sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  IPEndPoint ep2 = new IPEndPoint(IPAddress.Parse("X.Y.Z.W"), 1234);
  sendClient.Client.Bind(ep1);
  sendClient.Send(new byte[] { ... }, sizeOfBuffer, ep2);
}

Upvotes: 8

jasonp
jasonp

Reputation: 410

Use the same IPEndPoint for receiving that you used for sending.

UdpClient udpClient2 = new UdpClient(50177);
IPEndPoint Ip2 = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1005);
udpClient2.Send(peerto255, peerto255.Length, Ip2);
var dgram = udpClient2.Receive(ref Ip2);

Upvotes: 1

Related Questions