How do I find the port number assigned to a UDP client (in .net/C#)?
Asked Answered
M

2

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.

Malicious answered 21/8, 2009 at 23:45 Comment(0)
H
18

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;
Habergeon answered 21/8, 2009 at 23:57 Comment(4)
thanks. I'll implement this first thing Monday morning. What I was missing was the cast to IPEndPoint, so then intellisense didn't help me any. :(Malicious
Damn... never thought of that... thanx. :DPallor
Sadly, at least in .NET 4.0, the system never sets the Port field of a UDP socket. And since it is a get-only property, you can't manually set it either.Cheju
OOPS. I should have said: The system does not set the Port on RAW UDP Sockets when you bind. it does on DGRAM Sockets.Cheju
C
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;
}
Cheju answered 25/9, 2014 at 20:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.