5

使用 .NET,我如何在任何端口上收听发送到 .255 的 udp 广播数据包,而无需绑定到特定端口?

4

3 回答 3

6

我自己找到了办法。这是它的工作原理:

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);

在异步处理程序中,我执行 mainSocket.EndReceive(...),解析数据并在需要时启动新的 BeginReceive(从多线程接收器外部控制)。

奇迹般有效。致谢 Hitesh Sharma ( http://www.codeproject.com/KB/IP/CSNetworkSniffer.aspx )

于 2009-08-07T10:21:00.753 回答
4

我认为您需要低于 UDP 的级别才能完成此操作。

如果我真的想这样做,我会首先下载一个开源数据包嗅探器/网络分析器(想到Ethereal.com )并仔细阅读源代码以查看它们如何读取数据包。

进一步看,我在tcpdump.org发现了很多关于数据包捕获的信息。

抱歉我不能给出具体的代码片段,我一直想绑定到一个特定的端口。

于 2009-08-05T14:02:32.767 回答
0

您需要使用WinPCap或类似工具在链接级别嗅探数据包,然后过滤 UDP 广播。抱歉,我不认为有任何更高级别的 API。

于 2009-08-05T14:13:04.907 回答