2

我一直在尝试使用 SharpPcap 和 PacketDotNet 构建数据包嗅探器。到目前为止,这是我的代码:

public static void SniffConnection()
{
    var packets = new List<RawCapture>();
    var devices = CaptureDeviceList.Instance;
    PcapDevice device = null;

    foreach (var dev in devices)
    {
        if (((LibPcapLiveDevice)dev).Interface.FriendlyName.Equals("Wi-Fi 3"))
        {
            device = (LibPcapLiveDevice)dev;
            break;
        }
    }

    try
    {
        //Open the device for capturing
        device.Open(DeviceMode.Promiscuous);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        return;
    }

    //Register our handler function to the 'packet arrival' event
    device.OnPacketArrival += (sender, packets_storage) => PacketArrivalHandler(sender, ref packets);

    Console.WriteLine("sniffing...");
    try
    {
        device.Capture();
    }
    catch (System.AccessViolationException e)
    {
        Console.WriteLine(e);
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
    device.Close();
    Console.ReadLine();
}

public static void PacketArrivalHandler(object sender, ref List<RawCapture> packets)
{
    var dev = (WinPcapDevice)sender;
    RawCapture p = dev.GetNextPacket();
    if (p != null)
    {
        var raw_packet = Packet.ParsePacket(p.LinkLayerType, p.Data);       // split the packet into layers to check the data in layers is valid
        var tcpPacket = (TcpPacket)raw_packet.Extract(typeof(TcpPacket));
        var ipPacket = (IpPacket)raw_packet.Extract(typeof(IpPacket));
        packets.Add(p);
    }
}

在捕获了几个数据包后,Capture 函数会抛出异常,通常与内存有关。(访问冲突,内存不足,溢出)知道是什么原因造成的以及如何解决这个问题吗?(当抛出内存不足或溢出异常时,它表示它在 SharpPcap.LibPcap.PcapDevice.MarshalRawPacket 函数中,但是当抛出访问冲突时,它表示它发生在一个甚至与我的代码没有直接关系的 dll 中)

4

0 回答 0