捕获期间SharpPcap异常

时间:2016-02-08 13:09:29

标签: c# computer-science capture sharppcap

我一直在尝试使用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函数会抛出异常,通常是内存。 (访问冲突,内存不足,溢出) 知道是什么导致了这个以及如何解决这个问题? (当抛出Out of Memory或Overflow异常时,它表示它是SharpPcap.LibPcap.PcapDevice.MarshalRawPacket函数中的内容,但是当抛出Access Violation时,它表示它发生在一个甚至与我的代码无关的dll中)< / p>

0 个答案:

没有答案