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

大兔子大兔子 提交于 2019-12-10 13:27:12

问题


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.


回答1:


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;



回答2:


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;
}


来源:https://stackoverflow.com/questions/1314671/how-do-i-find-the-port-number-assigned-to-a-udp-client-in-net-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!