我自己找到了一种方法.这是它的工作原理:
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);
Run Code Online (Sandbox Code Playgroud)
在异步处理程序中,我执行一个mainSocket.EndReceive(...),解析数据并在需要时启动一个新的BeginReceive(从多线程接收器外部控制).
奇迹般有效.积分转到Hitesh Sharma(http://www.codeproject.com/KB/IP/CSNetworkSniffer.aspx)
我认为你需要比 UDP 更低的级别才能完成此任务。
如果我真的想这样做,我会首先下载一个开源数据包嗅探器/网络分析器(我想到了Ethereal.com )并仔细阅读源代码以了解它们如何读取数据包。
进一步看,我在tcpdump.org上发现了很多关于数据包捕获的信息。
抱歉,我无法提供具体的代码片段,我一直想绑定到特定的端口。