How to receive UDP packets from any ip and any port?

回眸只為那壹抹淺笑 提交于 2019-12-01 08:10:48

问题


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!


回答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




回答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.




回答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.



来源:https://stackoverflow.com/questions/3301134/how-to-receive-udp-packets-from-any-ip-and-any-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!