How to receive UDP packets from any ip and any por

2019-02-19 14:18发布

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!

3条回答
甜甜的少女心
2楼-- · 2019-02-19 15:04

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.

查看更多
贼婆χ
3楼-- · 2019-02-19 15:12

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

查看更多
欢心
4楼-- · 2019-02-19 15:13

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.

查看更多
登录 后发表回答