Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen for broadcast packets on any port?

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?

like image 458
Mephisztoe Avatar asked Aug 05 '09 12:08

Mephisztoe


People also ask

Does UDP have broadcast?

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.

What is broadcasting a packet in network?

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.

What broadcast forwarding?

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.

What is UDP forwarding?

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.


1 Answers

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)

like image 150
Mephisztoe Avatar answered Sep 17 '22 05:09

Mephisztoe