2

I've been trying to build a packet sniffer using SharpPcap and PacketDotNet. This is my code so far:

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);
    }
}

After a few packets are captured, the Capture function throws an exception, usually something about memory. (Access Violation, Out of Memory, Overflow) Any idea what's causing this and how to solve this? (when Out of Memory or Overflow exceptions are thrown, it says it's something in SharpPcap.LibPcap.PcapDevice.MarshalRawPacket function, but when the Access Violation is thrown, it says it's happenning in a dll thats not even related to my code directly)

Simon Karlsson
  • 4,090
  • 22
  • 39
user3554255
  • 41
  • 2
  • 8

0 Answers0