Posted By

pckujawa on 02/12/10


Tagged

ip ethernet networking udp


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

hinesnetwork
khouser


Listening for and receiving UDP packets on a particular local IP and port


 / Published in: C#
 

URL: http://msdn.microsoft.com/en-us/magazine/cc163648.aspx

For some reason, the only .NET way to listen for UDP packets seems to be the Bind and Receive(Async) methods of the Socket class. The Listen method won't work with UDP in my tests.

As for releasing the Socket correctly, this forum post explains that you must call Socket.Shutdown instead of Socket.Close (it also says to call Socket.Disconnect(true), but I get exceptions when I do that). If you want to reuse the local endpoint (IP and port), then do Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

While debugging Socket issues, it's helpful to have a command-line open and use the netstat tool (e.g. "netstat -a -p UDP" to show all UDP sockets on all local interfaces).

  1. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  2. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  3. string ip = "192.168.0.1";
  4. //ip = "0.0.0.0"; //any
  5. int port = 26010;
  6. socket.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
  7.  
  8. //socket.Listen(8); -> Listen doesn't work for UDP for some reason
  9. var buffer = new byte[1024];
  10. int numBytesReceived = socket.Receive(buffer);

Report this snippet  

You need to login to post a comment.