我自己找到了办法。它是这样工作的:
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 http://www.codeproject.com/KB/IP/CSNetworkSniffer.aspx)