如何接收任意IP、任意端口的UDP数据包?
我想使用 C# 的 UdpClient 来侦听任何传入的 UDP 数据包。我想从任何IP和任何端口接收数据包。
我尝试了以下方法:
UdpClient udpClient = new UdpClient(0);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 0);
byte[] data = udpClient.Receive(ref ep);
但没有成功。
有谁知道出了什么问题吗? 提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在任何端口上接收?那太疯狂了。您将被来自其他应用程序的消息淹没(尝试 TcpView 来了解一下每秒在您的系统上传递多少消息!)
您必须指定一个端口!端口有点像标识符——此数据包用于此程序(由端口号标识)
在任何端口上发送都是明智的,因为它要求系统为您选择一个端口发送OUT端口-- 有时这对于您的应用程序来说并不像发件人那么重要
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
您最好的想法是确定您想要监听的特定端口,然后开始监听这些端口。根据对收到的数据报的处理方式,最好/最简单的方法可能是为您正在侦听的每个端口创建一个新的
Thread
,并在那里处理它,或者将其排入同步队列(使用>lock
) 队列或列表,用于在中央线程上进行处理。不过你应该限制端口;不可能听取所有人的意见。
也就是说,您可以使用 Wireshark 或 Winpcap SDK/API 等工具直接从网络适配器“嗅探”UDP 数据包。我之前曾在 .NET 应用程序中使用过它,没有遇到太多困难。
希望有帮助。
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 (withlock
) 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 theWinpcap
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.
您需要侦听特定端口。
通过传入零,您将被分配一个任意端口,因此您将只收到发往该端口的 UDP 数据报。换句话说,你将一无所获。
如果您确实收到了某些内容,IPEndPoint 将填写有关发件人的信息。初始值可用于约束发送者。
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.