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