1. 用异步方式监听IP数据包
public class SniffSocket
{
private Socket socket;
private byte[] receiveBufferBytes;
private int receiveBufferLength;
private bool keepRunning = true;
private SniffSocket()
{
receiveBufferLength = 4096;
receiveBufferBytes = new byte[receiveBufferLength];
socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
socket.Blocking = false;
socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.100"), 0));
}
public void Run()
{
//Socket开始异步监听数据包,并利用委托AsyncCallback
//在相应异步操作完成时调用CallReceive方法进行处理。
IAsyncResult ar = socket.BeginReceive(receiveBufferBytes, 0,
receiveBufferLength, SocketFlags.None,
new AsyncCallback(CallReceive), this);
}
private void CallReceive(IAsyncResult ar)
{
int receivedBytes;
receivedBytes = socket.EndReceive(ar);//结束挂起的异步读取
Receive(receiveBufferBytes, receivedBytes);//解析接收的数据包
if (keepRunning) Run();//继续侦听
}
private void Receive(byte[] buf, int len)
{
//解析接收到的数据包
}
}
//-------------------------------------------------------------------------------------------------------------
以上代码是可以正常运行的
。
。
。
然后,我把[color=#FFFF00]socket.Blocking=false;注释掉,改成用同步方式来Receive()侦听接收,程序就无法接收到数据包了,原始套接字不能用同步方式来接收数据包么?
[/color]
------解决思路----------------------
那就贴出来.否则谁知道为什么,靠猜吗