I have just finished experimenting with UDP using C# and .NET 3.5 and thought it would be nice to throw the findings on the blog to stop myself loosing track of them.
Listening on port n
First of all, when you are listening for packets, it doesn’t matter whether that packet was only intended for you or it was a broadcast. Suppose you are member of an email group in your organisation. You receive emails sent to that group but you also receive emails that are sent only to you. The way you receive and read your emails is unaffected by the fact that whether it was sent to the whole group or just to you.
Similarly, when listening for UDP packets, you just get one when you should. So when we are listening for packets, life is simple and we just listen on given port:
socket.LocalEndPoint = new IPEndPoint (IPAddress.Any, n);
//Remote end point can be defined in following 2 ways:
socket.RemoteEndPoint = new IPEndPoint (IPAddress.Any, 0);
//or
socket.RemoteEndPoint = new IPEndPoint (IPAddress.Broadcast, 0);
Broadcasting on port n
If you wish to broadcast some packet to a given port, specifying local end point is not mandatory. If none is provided, a free port will be automatically picked. But we do need to specify remote end point:
//socket.LocalEndPoint = Not mandatory;
socket.RemoteEndPoint = new IPEndPoint (IPAddress.Broadcast, n);
Sending a packet on given IP address and port
If you wish to send an UDP packet to one computer specifically, you just need to define that IP address when setting remote end point. Local end point still remains optional:
//socket.LocalEndPoint = Not mandatory;
socket.RemoteEndPoint = new IPEndPoint (IPAddress.Parse("w.x.y.z"), n);