7

If I create a socket using

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

How do I then find the port of the socket?

I'm probably being daft, but I'm not having luck in MSDN/Google (probably because it is 4:42 on a Friday and the sun is shining).

Background:

What I want to do is find an open port, and then report to another process to forward messages to me on that port. There may be multiple clients, so I don't want to used a fixed port.

Thanks.

Charley Rathkopf
  • 4,720
  • 7
  • 38
  • 57

2 Answers2

17

UdpClient is a wrapper around the Socket class which exposes the endpoint it's bound to through the LocalEndPoint property. Since you're using an UDP/IP client it's an IPEndPoint which has the desired Port property:

int port = ((IPEndPoint)socket.Client.LocalEndPoint).Port;
dtb
  • 213,145
  • 36
  • 401
  • 431
0

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

goal:

  1. to create a RAW UDP socket on an arbitrary Port
  2. learn what port the system chose.

expected: (socket.LocalEndPoint as IPEndPoint).Port

problems

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

solution:

  1. create a normal DGRAM UDP socket
  2. bind that socket
  3. find out its Port
  4. close that normal socket
  5. create the RAW UDP socket

CAVEAT:

  • Use the modified local IPEndPoint variable to know the port, as the socket will always report 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;
}
Jesse Chisholm
  • 3,857
  • 1
  • 35
  • 29