views:

476

answers:

3

Using .NET, how can I listen to udp broadcast packets sent to .255 on any port without the need of binding to a specific port?

+3  A: 

I think you'll need to be lower level than UDP to accomplish this.

If I really wanted to do this, I'd start by downloading an open source packet sniffer/network analyzer (Ethereal.com comes to mind) and peruse the source to see how they read the packets.

Looking further, I found quite a bit about packet capturing at tcpdump.org.

Sorry I can't give specific code snippets, I've always wanted to bind to a specific port.

MrAleGuy
A: 

You'll need to use WinPCap or similar to sniff packets at the link level, then filter for UDP broadcasts. Sorry, I don't think there's any higher level API for this.

bdonlan
+2  A: 

I found a way myself. This is how it works:

mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
mainSocket.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.1"), 0));
mainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);                           

byte[] byTrue = new byte[4] { 1, 0, 0, 0 };
byte[] byOut = new byte[4] { 1, 0, 0, 0 }; 

// Socket.IOControl is analogous to the WSAIoctl method of Winsock 2
mainSocket.IOControl(IOControlCode.ReceiveAll, //Equivalent to SIO_RCVALL constant of Winsock 2
    byTrue,
    byOut);

//Start receiving the packets asynchronously
mainSocket.BeginReceive(byteData,0,byteData.Length,SocketFlags.None,new AsyncCallback(OnReceive),null);

In the async handler, I do a mainSocket.EndReceive(...), parse the data and start a new BeginReceive if wanted (controlled from outside the multithreaded receiver).

Works like a charm. Credits go to Hitesh Sharma (http://www.codeproject.com/KB/IP/CSNetworkSniffer.aspx)

Mephisztoe