How to find the port number assigned to a UDP client (in .net / C #)?

If I create a socket using

var socket = new UdpClient(0,AddressFamily.InterNetwork); 

How do I find the socket port?

I'm probably stupid, but I had no luck on MSDN / Google (perhaps because Friday is 4:42 on Friday and the sun is shining).

Background:

What I want to do is find the open port, and then tell another process to forward me messages on that port. There may be several clients, so I do not want to use a fixed port.

Thanks.

+4
source share
2 answers

UdpClient is a Socket class wrapper that provides the endpoint to which it is connected through the LocalEndPoint property. Since you are using a UDP / IP client, this is IPEndPoint, which has the required port property:

 int port = ((IPEndPoint)socket.Client.LocalEndPoint).Port; 
+11
source

For those (like me) who need to use a RAW socket, here is a workaround.

Goal:

  • to create a RAW UDP socket on an arbitrary port
  • Find out which port the system has selected.

Expected: (socket.LocalEndPoint as IPEndPoint) .Port

Problems

  • whereas DGRAM UDP Socket knows its own (socket.LocalEndPoint as IPEndPoint) .Port
  • RAW UDP Socket always returns zero

decision:

  • create normal UDP DGRAM connector
  • bind this socket
  • find out his port
  • close this regular socket
  • create RAW UDP socket

CAVEAT:

  • Use the modified local IPEndPoint variable to know the port, as the socket will always indicate zero.

code:

 public Socket CreateBoundRawUdpSocket(ref IPEndPoint local) { if (0 == local.port) { Socket wasted = new Socket(local.AddressFamily, SocketType.Dgram, ProtocolType.Udp); wasted.Bind(local); local.Port = (wasted.LocalEndPoint as IPEndPoint).Port; wasted.Close(); } Socket goal = new Socket(local.AddressFamily, SocketType.Raw, ProtocolType.Udp); goal.Bind(local); return goal; } 
0
source

All Articles