使用.NET,如何在任何端口上监听发送到.255的udp广播数据包,而无需绑定到特定端口?
我自己找到了一种方法.这是它的工作原理:
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)