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?
UDP Broadcast is an automatic method that can be used without manually entering the IP address of all Audia/Nexia devices. TCP can be used only if the exact IP addresses are known and can be entered manually.
In computer networking, broadcasting refers to transmitting a packet that will be received by every device on the network. In practice, the scope of the broadcast is limited to a broadcast domain.
A directed broadcast is an IP broadcast to all devices within a single directly-attached network or subnet. A net-directed broadcast goes to all devices on a given network. A subnet-directed broadcast goes to all devices within a given subnet.
User Datagram Protocol (UDP) forwarding is a feature used in Cisco IOS software to forward broadcast and multicast packets received for a specific IP address.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With