How to receive UDP packets from any ip and any port?
Solution 1
RECEIVE on any port? That's insane. You would be flooded with messages from other applications (try TcpView for an idea of how many messages get passed on your system per second!)
You must specify a port! Port is sort of like an identifier -- this packet is meant for THIS program (identified by port #)
Send on any port is sensible, as it asks the system to choose a port send OUT port for you -- which isn't really that important to your application as the sender sometimes
Solution 2
Your best idea would be to identify specific ports you would like to listen to, and start listening on those. Depending on what is done with received datagrams, it might be best/simplest to create a new Thread
for each port you are listening on, and process it there, or enqueue it on a synchonrised (with lock
) queue or list, for processing on a central thread.
You should limit the ports though; it would not be possible to listen to them all.
That said you could use something like Wireshark
or the Winpcap
SDK/API to 'sniff' UDP packets right from the network adapter. I have had it working within a .NET application before without too much difficulty.
Hope that helps.
Solution 3
You need to listen on a specific port.
By passing in zero, you are assigned an arbitrary port, so you will receive only UDP datagrams addressed to it. In other words, you will receive nothing.
If you did receive something, the IPEndPoint would be filled in with information about the sender. The initial value could be used to constrain the sender.
Related videos on Youtube
raisyn
Master's Student at Vienna University of Technology Interested in various topics of computer science.
Updated on April 28, 2022Comments
-
raisyn about 2 years
I wanted to use C#'s UdpClient to listen to any incomming UDP packets. I want to receive packets from any IP and any port.
I tried the following:
UdpClient udpClient = new UdpClient(0); IPEndPoint ep = new IPEndPoint(IPAddress.Any, 0); byte[] data = udpClient.Receive(ref ep);
but without success.
Does anyone know whats wrong? Thanks in advance!
-
MPritchard almost 14 years@Fosco: Network sniffer?
-
Steven Sudit almost 14 years@MPritch: Then that's not really UDP. You'd be listening on raw ethernet packets.
-
Jesse Chisholm over 9 yearsre: Network Sniffer? Then that's not really UDP. -- then call it UDP Sniffer. ;-D
-
-
Jesse Chisholm over 9 yearsIncase or not, there are legitimate reasons to want this. And it is do-able with RAW+UDP socket in promiscuous mode (and running at Administrator level).
-
Mud almost 7 yearsHow is it "insane" to receive on any port, but not insane to send on any port? If the logic is that that the port identifies which program the packets are meant for, that would apply to both sending and receiving, right?