问题
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:
- to create a RAW UDP socket on an arbitrary Port
- 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:
- create a normal DGRAM UDP socket
- bind that socket
- find out its Port
- close that normal socket
- 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