我正在尝试使用C#打包嗅探器,并且我想自己编写它,仅使用C#方法而不依赖于其他作者。我正在使用BeginReceiveFrom方法,并且仅捕获到LAN中设备(192.168.0.87)和来自设备的包以及两个地址:224.0.0.251:5353、255.255.255.255:57621。当然,在局域网中的设备上,我打开了网站以确保其中的软件包正在通过网络。我做错了什么? :-)感谢您的帮助!
静态无效嗅探器(IPAddress ip){
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
sck.Bind(new IPEndPoint(ip, 0));
sck.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
sck.IOControl(IOControlCode.ReceiveAll, new byte[4] { 1, 0, 0, 0 }, null);
byte[] buffer = new byte[24];
Action<IAsyncResult> OnReceive = null;
EndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.0.87"), 0);
OnReceive = (ar) =>
{
String sourceIp = SourceIP(buffer);
String destinationIp = DestinationIp(buffer);
if (sourceIp != ip.ToString() && destinationIp != ip.ToString())
{
Console.WriteLine(
"{0}\t{1}:{2}\t===>\t{3}:{4}"
, buffer.Skip(9).First().ToProtocolString()
, SourceIP(buffer)
, ((ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 20))).ToString()
, DestinationIp(buffer)
, ((ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 22))).ToString());
}
buffer = new byte[24]; //clean out our buffer
//sck.BeginReceive(buffer, 0, 24, SocketFlags.None, new AsyncCallback(OnReceive), null);
sck.BeginReceiveFrom(buffer, 0, 24, SocketFlags.None, ref endPoint, new AsyncCallback(OnReceive), null);
};
// sck.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref endPoint, new AsyncCallback(OnReceive), null);
}
private static String SourceIP(byte[] buffer)
{
return new IPAddress(BitConverter.ToUInt32(buffer, 12)).ToString();
}
private static String DestinationIp(byte[] buffer)
{
return new IPAddress(BitConverter.ToUInt32(buffer, 16)).ToString();
}
public static string ToProtocolString(this byte b)
{
switch (b)
{
case 1: return "ICMP";
case 6: return "TCP";
case 17: return "UDP";
default: return "#" + b.ToString();
}
}
我仅看到一些往返于地址224.0.0.251:5353、255.255.255.255:57621的软件包。我希望能看到局域网中来自/到设备的整个通信。