Search code examples
c#sharppcappacketdotnet

SharpPcap: OnPacketArrival Event Not Firing


Subscribing to the OnPacketArrival event does not work. Any idea what I do wrong?

using System;
using PacketDotNet;
using SharpPcap;

Console.WriteLine("Starting packet capture...");

var devices = CaptureDeviceList.Instance;

if (devices.Count == 0)
{
    Console.WriteLine("No network devices found.");
    return;
}

var device = devices[0];
Console.WriteLine(device.ToString());

try
{
    device.Open();

    device.OnPacketArrival += (sender, e) =>
    {
        try
        {
            var packet = Packet.ParsePacket(e.GetPacket().LinkLayerType, e.GetPacket().Data);

            if (packet is EthernetPacket ethernetPacket)
            {
                if (ethernetPacket.PayloadPacket is IPPacket ipPacket)
                {
                    if (ipPacket.DestinationAddress.ToString() == "54.220.192.176" &&
                        ipPacket.PayloadPacket is TcpPacket tcpPacket &&
                        tcpPacket.DestinationPort == 443) // HTTPS port
                    {
                        var sourceIp = ipPacket.SourceAddress;
                        var destinationIp = ipPacket.DestinationAddress;
                        var sourcePort = tcpPacket.SourcePort;
                        var destinationPort = tcpPacket.DestinationPort;

                        Console.WriteLine($"HTTPS Packet: Source IP: {sourceIp}, Source Port: {sourcePort}, Destination IP: {destinationIp}, Destination Port: {destinationPort}");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error processing packet: {ex.Message}");
        }
    };

    device.StartCapture();

    Console.WriteLine("Capturing packets. Press ENTER to stop.");
    Console.ReadLine();

    device.StopCapture();
}
catch (Exception ex)
{
    Console.WriteLine($"Error capturing traffic: {ex.Message}");
}
finally
{
    device.Close();
}

Solution

  • I tested your code out in a C# environment and found that the OnPacketArrival event does fire, but only on devices that actually receive packets.

    Debug your code and find out what device in devices is definitely receiving packets, then replace your index to the corresponding device.

    var device = devices[0]; // Is this device even receiving packets? Perhaps another index will work
    Console.WriteLine(device.ToString());