Click here to Skip to main content
11,927,190 members (43,103 online)
Click here to Skip to main content
Add your own
alternative version


491 bookmarked

SharpPcap - A Packet Capture Framework for .NET

, , 5 May 2014 MPL
Rate this:
Please Sign up or sign in to vote.
A framework for capturing, injecting and analyzing network packets for .NET applications based on the WinPcap packet capture driver

[A .NET sniffer application written with SharpPcap]


Packet capturing (or packet sniffing) is the process of collecting all packets of data that pass through a given network interface. Capturing network packets in our applications is a powerful capability which lets us write network monitoring, packet analyzers and security tools. The libpcap library for UNIX based systems and WinPcap for Windows are the most widely used packet capture drivers that provide API for low-level network monitoring. Among the applications that use libpcap/WinPcap as its packet capture subsystem are the famous tcpdump and Wireshark.

In this article, we will introduce the SharpPcap .NET assembly (library) for interfacing with libpcap or winpcap from your .NET application and will give you a detailed programming tutorial on how to use it.


Tamir Gal started the SharpPcap project around 2004. He wanted to use WinPcap in a .NET application while working on his final project for university. The project involved analyzing and decoding VoIP traffic and he wanted to keep coding simple with C# which has time saving features like garbage collection. Accessing the WinPcap API from .NET seemed to be quite a popular requirement, and he found some useful projects on CodeProject's website that let you do just that.

The projects available at the time did not lend themselves to being used to capture and analyze traffic. Some had mixed ui and capture code, others had reimplemented some of WinPcap's functions in C# and others lacked features such as offline file reading or source code.

And so, Tamir decided to start his own library for the task. Several versions in the 1.x series were released. Development slowed towards mid-2007 when the last version in the 1.x series was released, SharpPcap 1.6.2.

Chris Morgan took over development of SharpPcap in November of 2008. Since then SharpPcap has had major internal rewrites and API improvements including Linux, Mac support.

In late February 2010 SharpPcap v3.0 was released. This release represents a rewrite of SharpPcap's packet parsers. Packet parsing functionality was broken out into a new library, Packet.Net. SharpPcap takes care of interfacing with libpcap/winpcap and Packet.Net takes care of packet dissection and creation. The details of Packet.Net's architecture will be discussed later in the turotial.

SharpPcap v3.5 was released February 1st, 2011. The 3.5 release contained significant API changes as well as WinPcap remote capture and AirPcap support.

SharpPcap v4.0 was released September 13, 2011. The 4.0 release contains significant performance improvements due to contributions from Michael Giagnocavo. SharpPcap 4.0 is >50% faster than the last revision, v3.7. It also contains API cleanup for reading and writing to capture files in the form of new CaptureFileWriterDevice and CaptureFileReaderDevice that replaces an older and much more confusing way of writing to capture files and makes reading and writing analogous.

SharpPcap v4.2 was released January 14th, 2013. 4.2 adds support for IEEE 802.1Q vlan tags, corrects access modifiers in Packet to enable 3rd party assemblies to use this class and introduces Packet.Extract(). Packet.Extract() replaces per-packet GetEncapsulated() methods, now deprecated, with a single high level routine that is a part of the base class of all captured packets.

About SharpPcap

The purpose of SharpPcap is to provide a framework for capturing, injecting and analyzing network packets for .NET applications.

SharpPcap is openly and actively developed with its source code and file releases hosted on SourceForge. Source code patches to improve or fix issues are welcome via the sharppcap developers mailing list. Bug reports, feature requests and other queries are actively answered on the support forums and issue trackers there so if you have any trouble with the library please feel free to ask.

SharpPcap is a fully managed cross platform library. The same assembly runs under Microsoft .NET as well as Mono on both 32 and 64bit platforms.

The following list illustrates the features currently supported by SharpPcap:

  • Single assembly for Microsoft .NET and Mono platforms on Windows (32 or 64bit), Linux (32 or 64bit) and Mac.
  • High performance - SharpPcap can capture fast enough to keep up with >3MB/s scp transfer rates
  • WinPcap extensions are partially supported:
    • Remote packet capture
    • Setting the kernel buffer size
    • Injecting packets using send queues.
    • Collecting network statistics on a given network interface
  • AirPcap support
  • Enumerating and showing details about the physical network interface on a Windows machine.
  • Capturing low-level network packets going through a given interface.
  • Packet.Net is used for packet parsing
  • Injecting low-level network packets on a given interface.
  • Handling (reading and writing) packet capture files.
  • Retrieving adapter statistics on packets received vs. dropped
Packet.Net supports analyzing and parsing the following protocols:

Please check the project homepage homepage for the latest updates and bug fixes.

SharpPcap architecture

SharpPcap has a layered architecture, at the top level are classes that work across all devices:

  • CaptureDeviceList - Retrieves a list of all devices on the system
  • ICaptureDevice - All capture devices have ICaptureDevice interfaces
The namespaces are layed out hierarchically:
  • LibPcap
    • LibPcapLiveDevice - A ICaptureDevice
    • LibPcapLiveDeviceList - Retrieves a list of LibPcapLiveDevice devices (these include pcap/winpcap and airpcap devices)
    • CaptureFileReaderDevice - Device that reads from a pcap capture file
    • CaptureFileWriterDevice - Device that creates or writes to a pcap format capture file
  • WinPcap
    • WinPcapDeviceList - Retrieves a list of WinPcapDevices (these include winpcap and airpcap devices)
    • WinPcapDevice - A LibPcapLiveDevice with additional WinPcap features and interfaces
  • AirPcap
    • AirPcapDeviceList - Retrives a list of AirPcapDevices
    • AirPcapDevice - A WinPcapDevice with additional AirPcap features and interfaces
CaptureDeviceList returns a list of fully differentiated devices. This means that each ICaptureDevice returned by CaptureDeviceList is either a LibPcapLiveDevice, a WinPcapDevice or a AirPcapDevice. This allows you to retrieve the entire list of devices and differentiate by looking at the type of each device. If you would like to get a specific type of device only you can use one of the particular *DeviceList classes.
// Retrieve all capture devices
var devices = CaptureDeviceList.Instance;

// differentiate based upon types
foreach(ICaptureDevice dev in devices)
  if(dev is AirPcapDevice)
    // process as an AirPcapDevice
  } else if(dev is WinPcapDevice)
    // process as an WinPcapDevice
  } else if(dev is LibPcapLiveDevice)
    // process as an LibPcapLiveDevice

// Retrieve only WinPcap (and AirPcap devices)
var devices = AirPcapDeviceList.Instance;
foreach(AirPcapDevice dev in devices)
  // Process this AirPcap device

Packet.Net architecture and usage

Packet.Net switched from the inheritance model of SharpPcap 2.x to one of nesting packets. Avoiding inheritance makes Packet.Net more flexible and simplifies the construction of complex packets. While the inheritance model made some things easier, a UdpPacket for instance had a SourceHwAddress (the parent Ethernet packet's source mac address field), it also made things very difficult. What about Ethernet packets that were themselves inside of other packets? When a udp packet was created do I need to specify all of its fields and the fields of all of its parents? The nesting approach solves these problems by separating the different packet layers, and things like Packet.Extract(), discussed further on, make it easy to retrieve sub-packets.

All packets contain a Packet PayloadPacket property and a Byte[] PayloadData property. One or neither of these can be valid. A Tcp packet captured on Ethernet may be EthernetPacket -> IPv4 Packet -> Tcp Packet. In Packet.Net the Tcp packet could be accessed like capturedPacket.PayloadPacket.PayloadPacket but to to aid users Packet.Extract(System.Type type) was created so you can do TcpPacket tcpPacket = (TcpPacket)capturedPacket.Extract(typeof(TcpPacket));.

The Packet.Extract() is a uniform method that, when given a type, will retrieve the nested packet of that given type. If 'p' is a udp packet, then (UdpPacket)p.Extract(typeof(UdpPacket) will return the Udp packet of a packet that consists of EthernetPacket -> IP packet -> UdpPacket or Linux Cooked Capture -> IP -> UdpPacket or an EthernetPacket -> PPPoE -> PTP -> IP -> UdpPacket. We recommend using the Packet.Extact() approach rather than the older and now deprecated GetEncapsulated() methods, or other more manual approaches.

With Packet.Net constructing packets looks like:

using PacketDotNet;

ushort tcpSourcePort = 123;
ushort tcpDestinationPort = 321;
var tcpPacket = new TcpPacket(tcpSourcePort, tcpDestinationPort);

var ipSourceAddress = System.Net.IPAddress.Parse("");
var ipDestinationAddress = System.Net.IPAddress.Parse("");
var ipPacket = new IPv4Packet(ipSourceAddress, ipDestinationAddress);

var sourceHwAddress = "90-90-90-90-90-90";
var ethernetSourceHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(sourceHwAddress);
var destinationHwAddress = "80-80-80-80-80-80";
var ethernetDestinationHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(destinationHwAddress);

// NOTE: using EthernetPacketType.None to illustrate that the Ethernet
//       protocol type is updated based on the packet payload that is
//       assigned to that particular Ethernet packet
var ethernetPacket = new EthernetPacket(ethernetSourceHwAddress,

// Now stitch all of the packets together
ipPacket.PayloadPacket = tcpPacket;
ethernetPacket.PayloadPacket = ipPacket;

// and print out the packet to see that it looks just like we wanted it to

// to retrieve the bytes that represent this newly created EthernetPacket use the Bytes property
byte[] packetBytes = ethernetPacket.Bytes;

SharpPcap tutorial: A step by step guide to using SharpPcap

These and many other examples can be found in the Examples/ directory of the source package. Go to the SharpPcap files page, select the release directory you want and download the package named like

The text of this tutorial was taken directly from WinPcap's official tutorial but is modified to show the C# use of the SharpPcap library. All examples can be downloaded together with the SharpPcap source code from the top of this page. If you are running on Windows, the WinPcap library must be installed before attempting to run any of these examples so please download and install the latest version from WinPcap's download page. If running under unix/linux/mac the libpcap library must be installed using your systems software management system.

The following topics are covered in this tutorial with the name of the example in parenthesis:

  1. Obtaining the device list (Example 1)
  2. Opening an adapter and capturing packets (Example 3)
  3. Capturing packets without the event (Example 4)
  4. Filtering the traffic (Example 5)
  5. Writing packets to a capture file (CreatingCaptureFile)
  6. Reading packets from a capture file (ReadingCaptureFile)
  7. Interpreting the packets (Example 6)
  8. Sending packets (Example 9)
  9. Send Queues (Example 10) - WinPcap only
  10. Gathering statistics on the network traffic (Example 11) - WinPcap only
  11. Queuing packets for background processing - High packet rate capture

Obtaining the device list (Example 1 in the source package)

Typically, the first thing that a SharpPcap-based application does is get a list of attached network adapters. SharpPcap provides a class, CaptureDeviceList for this purpose. The class is a singleton instance that holds a cached list of network adapters of type ICaptureDevice. In particular, the Name and Description properties contain the name and a human readable description, respectively, of the corresponding device. The following C# sample shows how to retrieve a list of adapters and print it on the screen, printing an error if no adapters are found:

// Print SharpPcap version 
string ver = SharpPcap.Version.VersionString;
Console.WriteLine("SharpPcap {0}, Example1.IfList.cs", ver);

// Retrieve the device list
CaptureDeviceList devices = CaptureDeviceList.Instance;

// If no devices were found print an error
if(devices.Count < 1)
    Console.WriteLine("No devices were found on this machine");

Console.WriteLine("\nThe following devices are available on this machine:");

// Print out the available network devices
foreach(ICaptureDevice dev in devices)
    Console.WriteLine("{0}\n", dev.ToString());

Console.Write("Hit 'Enter' to exit...");

The output of the above application will be as something like this:

SharpPcap, Example1.IfList.cs

The following devices are available on this machine:

interface: Name: \Device\NPF_{D8B7C9B2-D53D-45DA-ACF0-2E2116F97314}
FriendlyName: Local Area Connection 2
Description: Intel(R) PRO/1000 MT Desktop Adapter
Addr:      fe80::b444:92d8:c882:8227


Addr:      HW addr: 0800276AC792

Flags: 0

Hit 'Enter' to exit...

Opening an adapter and capturing packets (Example 3 in the source package)

Now that we've seen how to obtain an adapter to play with, let's start the real job, opening an adapter and capturing some traffic. In this section, we'll write a program that prints some information about each packet flowing through the adapter.

The function that opens a device for capture is Open() which is overloaded with some arguments as follows:

  • Open()
  • Open(DeviceMode mode)
  • Open(DeviceMode mode, int read_timeout)

The above two arguments deserve some further explanation.

DeviceMode In normal mode (DeviceMode.Normal), a network adapter only captures packets addressed directly to it; the packets exchanged by other hosts on the network are ignored. Instead, when the adapter is in promiscuous mode (DeviceMode.Promiscuous) it captures all packets whether they are destined to it or not. This means that on shared media (like non-switched Ethernet), libpcap/WinPcap will be able to capture the packets of other hosts. Promiscuous mode is the default for most capture applications, so we enable it in the following example. NOTE: Promiscuous mode can be detected via network means so if you are capturing in promiscuous mode you may be able to be detected by other entities on the network. Search for "detect promiscuous" via a web search engine for more information.

read_timeout: Specifies the read timeout, in milliseconds. A read on the adapter (for example, using the GetNextPacket() function) will always return after read_timeout milliseconds, even if no packets are available from the network. read_timeout also defines the interval between statistical reports if the adapter is in statistical mode (see the Gathering statistics on the network traffic section). Setting read_timeout to 0 means no timeout, a read on the adapter never returns if no packets arrive. A -1 timeout on the other side causes a read on the adapter to always return immediately.

The following example shows the use of the OnPacketArrival event for receiving packets. We create an event handler that is being called whenever a new packet is going through the ICaptureDevice:

// Extract a device from the list
ICaptureDevice device = devices[i];

// Register our handler function to the
// 'packet arrival' event
device.OnPacketArrival +=
    new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);

// Open the device for capturing
int readTimeoutMilliseconds = 1000;
device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

Console.WriteLine("-- Listening on {0}, hit 'Enter' to stop...",

// Start the capturing process

// Wait for 'Enter' from the user.

// Stop the capturing process

// Close the pcap device

And here is our packet handler implementation:

/// <summary>
/// Prints the time and length of each received packet
/// </summary>
private static void device_OnPacketArrival(object sender, CaptureEventArgs packet)
    DateTime time = e.Packet.Timeval.Date;
    int len = e.Packet.Data.Length;
    Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
        time.Hour, time.Minute, time.Second, time.Millisecond, len);

Once the adapter is opened, the capture can be started with the StartCapture() or Capture(int packetCount) functions. These two functions are very similar, the difference is that StartCapture() is a non-blocking function that starts the capturing process on a new thread, while Capture(int packetCount) blocks until packetCount packets have been captured. When using StartCapture() we should later call StopCapture() to terminate the capture process. To capture indefinitely call the Capture() method.

Both of these functions require that an event handler for processing packets registered prior to calling them. This event handler is invoked by ICaptureDevice for every new packet coming from the network and receives the sender object that invoked this handler (i.e. the ICaptureDevice object) and the actual received Packet, including all the protocol headers. Note that the frame CRC is normally not present in the packet, because it is removed by the network adapter after the frame validation. Note also that most adapters discard packets with wrong CRCs, so WinPcap (and therefore SharpPcap) is normally not able to capture them.

The Packet class represents a generic packet captured from the network. Each such packet has a PcapHeader property containing some info (e.g. the timestamp of the capture and the length of the packet) about the captured packet. The above example extracts the timestamp and the length from every Packet object and prints them on the screen.

Please note that the handler code is called by the ICaptureDevice; therefore the user application does not have direct control over it. Another approach is to use the GetNextPacket() function, which is presented in the next section.

Capturing packets without the event handler (Example 4 in the source package)

The example program in this section behaves exactly like the previous sample, but it uses ICaptureDevice.GetNextPacket() method instead of registering an event handler. The OnPacketArrival event is a good practice and could be a good choice in some situations, such as when capturing from several devices at once. However, handling a callback is sometimes not practical - it often makes the program more complex especially in situations with multithreaded applications. In these cases, GetNextPacket() retrieves a packet with a direct call - using GetNextPacket(), packets are received only when the programmer wants them. In the following program, we re-use the event handler code of the previous example and move it into a loop in the main function right after the call to GetNextPacket().

Note: The following example will exit if the timeout of 1000 ms expires with no packets on the network:

// Extract a device from the list
ICaptureDevice device = devices[i];

// Open the device for capturing
int readTimeoutMilliseconds = 1000;
device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

Console.WriteLine("-- Listening on {0}...",

Packet packet = null;

// Keep capture packets using GetNextPacket()
while((packet=device.GetNextPacket()) != null )
    // Prints the time and length of each received packet
    DateTime time = packet.PcapHeader.Date;
    int len = packet.PcapHeader.PacketLength;
    Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
        time.Hour, time.Minute, time.Second,
        time.Millisecond, len);

// Close the pcap device
Console.WriteLine(" -- Capture stopped, device closed.");

Filtering the traffic (Example 5 in the source package)

One of the most powerful features offered by libpcap and WinPcap is the filtering engine. It provides a very efficient way to receive subsets of the network traffic. WinPcap and libpcap have an integrated compiler that takes a string containing a high-level Boolean (filter) expression and produces a low-level byte code that can be interpreted by the filter engine of the packet capture driver. The syntax (also known as the tcpdump syntax) of the boolean expression is widely used in many applications other than WinPcap and libpcap. You can find its spec in WinPcap's documentation page or if you are running linux via 'man pcap-filter'.

The Filter property associates a filter with a capture adapter. Once Filter is set, the associated filter will be applied to all the packets coming from the network, and all the conformant packets (i.e., packets for which the boolean expression evaluates to true) will be actually copied to the application. The following code shows how to compile and set a filter.

Note that libpcap/winpcap's expression compiler requires that the netmask of the ICaptureDevice to be passed together with the filter, because some filters created by the compiler require it. However SharpPcap takes care of it for us by automatically extracting the netmask from the adapter.

The filter expression we use in the following snippet is "ip and tcp", which means to "keep only the packets that are both IPv4 and TCP and deliver them to the application":

// Open the device for capturing
int readTimeoutMilliseconds = 1000;
device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

// tcpdump filter to capture only TCP/IP packets
string filter = "ip and tcp";
device.Filter = filter;

Console.WriteLine("-- The following tcpdump filter will be applied: \"{0}\"",
Console.WriteLine("-- Listening on {0}, hit 'Enter' to stop...",

// Start capturing packets indefinitely

// Close the pcap device
// (Note: this line will never be called since
// we're capturing indefinitely

Writing packets to a file (CreatingCaptureFile example in the source package)

It is useful to be able to write captured packets to a file for offline processing, keeping records etc. Recently SharpPcap gained a new class for writing capture files, CaptureFileWriterDevice. In this example we will be capturing packets from a network device and writing them to a newly created capture file.

To write packets to a capture file create a CaptureFileWriterDevice. In this case we are creating one using the settings from capture device called 'device'. Capture files need to know the link layer type, a PacketDotNet.LinkLayers, and the capture packet length. CaptureFileWriterDevice will determine these if given an existing capture device of type LibPcap.LibPcapLiveDevice, or there are other constructors that take them as parameters.

// open the output file
captureFileWriter = new CaptureFileWriterDevice(device, capFile);

Now that the captureFileWriter exists we can look at the OnPacketArrival handler to see how simple it is to write them to disk:

// write the packet to the file
Console.WriteLine("Packet dumped to file.");

Reading packets from a file (ReadingCaptureFile example in the source package)

Reading packets from a capture file is also quite simple. Create an instance of CaptureFileReaderDevice(string captureFilename) and read packets as you would from any device. The ReadingCaptureFile example sets this up like:

// Register our handler function to the 'packet arrival' event
device.OnPacketArrival +=
      new PacketArrivalEventHandler( device_OnPacketArrival );

      ("-- Capturing from '{0}', hit 'Ctrl-C' to exit...",

// Start capture 'INFINTE' number of packets
// This method will return when EOF reached.

Interpreting the packets (Example 6 in the source package)

Now that we are able to capture and filter network traffic, we want to put our knowledge to work with a simple "real world" application. In this lesson, we will take the code from the previous sections and use these pieces to build a more useful program. The main purpose of the current program is to show how the protocol headers of a captured packet can be parsed and interpreted. The resulting application, called DumpTCP, prints a summary of the TCP traffic on our network. I have chosen to parse and display the TCP protocol (rather than the UDP example posted in the original tutorial) because it is a bit more interesting than UDP and with SharpPcap it doesn't require too much parsing coding.

/// <summary>
/// Prints the time, length, src ip,
/// src port, dst ip and dst port
/// for each TCP/IP packet received on the network
/// </summary>
private static void device_OnPacketArrival(
    object sender, CaptureEventArgs e)
    var tcp = (TcpPacket)e.Packet.Extract(typeof(TcpPacket));
    if(tcp != null)
        DateTime time = e.Packet.Timeval.Date;
        int len = e.Packet.Data.Length;
        string srcIp = tcp.SourceAddress;
        string dstIp = tcp.DestinationAddress;

        Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
            time.Hour, time.Minute, time.Second,
            time.Millisecond, len);

If you take a look at the UDP example of the original WinPcap tutorial you will see how complex it is to parse the packets (although UDP is a bit simpler to parse than TCP in our example) directly from the raw data bytes provided by the WinPcap library. Luckily for us, SharpPcap provides some useful packet analyzing classes for some common protocols (e.g. TCP, UDP, ICMP and others). These analyzing classes were initially a direct C# translation from JPcap, a Java wrapper for libpcap/WinPcap similar to SharpPcap, but significant changes have been made to make them fit better into .NET. All of the packet parsing and generation code can be found in the PacketDotNet namespace in the PacketDotNet assembly.

As you can see, in our packet handler we first attempt to extract the Tcp packet encapsulated in the packet that was captured on the line. If one was found, and it should be since our filter selects only tcp packets, we can then access its properties. If we also wanted to see the IP packet properties these could be accessed via var ip = (IpPacket)e.Packet.Extract(typeof(IpPacket));

Available devices:

1) Intel(R) PRO/1000 MT Mobile Connection
   (Microsoft's Packet Scheduler)

-- Please choose a device to capture: 1

-- Listening on Intel(R) PRO/1000 MT Mobile Connection
-- (Microsoft's Packet Scheduler)...
1:18:17,675 Len=123 ->
1:18:17,675 Len=80 ->
1:18:17,919 Len=54 ->

Each of the final three lines represents a different packet.

Sending packets (Example 9 in the source package)

The simplest way to send a packet is shown in the following code snippet. After opening an adapter, SendPacket is called to send a hand-crafted packet. SendPacket takes as argument a byte array or a Packet object containing the data to be sent. Notice that the buffer is sent to the network as it was received. This means that the application has to create the correct protocol headers in order to send something meaningful:

// Open the device

// Generate a random packet
byte[] bytes = GetRandomPacket();

    // Send the packet out the network device
    device.SendPacket( bytes );
    Console.WriteLine("-- Packet sent successfuly.");
catch(Exception e)
    Console.WriteLine("-- "+ e.Message );

// Close the pcap device
Console.WriteLine("-- Device closed.");

Send queues - WinPcap specific extension (Example 10 in the source package)

While SendPacket offers a simple and immediate way to send a single packet, send queues provide an advanced, powerful and optimized mechanism to send a collection of packets. A send queue is a container for a variable number of packets that will be sent to the network. It has a size, that represents the maximum amount of bytes it can store.

Because SendQueue functionality is WinPcap specific the authors of SharpPcap recommend benchmarking your particular usage of sending packets to determine if the loss of cross platform support is worth the added efficiency of using send queues. The old adage, "avoid premature optimization" should be carefully considered.

SharpPcap represents a send queue using the SendQueue class which is constructed by specifying the size of the new send queue.

Once the send queue is created, SendQueue.Add() can be called to add a packet to the send queue. This function takes a PcapHeader with the packet's timestamp and length and a buffer or a Packet object holding the data of the packet. These parameters are the same as those received by the OnPacketArrival event, therefore queuing a packet that was just captured or a read from a file is a matter of passing these parameters to SendQueue.Add().

To transmit a send queue, SharpPcap provides the WinPcapDevice.SendQueue(SendQueue q, SendQueueTransmitModes transmitMode) function. Note the second parameter: if SendQueueTransmitModes.Synchronized, the send will be synchronized, i.e. the relative timestamps of the packets will be respected. This operation requires a remarkable amount of CPU, because the synchronization takes place in the kernel driver using "busy wait" loops. Although this operation is quite CPU intensive, it often results in very high precision packet transmissions (often around few microseconds or less).

Note that transmitting a send queue with WinPcapDevice.SendQueue() is more efficient than performing a series of ICaptureDevice.SendPacket(), since the send queue buffered at kernel level drastically decreases the number of context switches.

When a queue is no longer needed, it can be deleted with SendQueue.Dispose() that frees all the buffers associated with the send queue.

The next program shows how to use send queues. It opens a capture file by creating a CaptureFileReaderDevice(), then it stores the packets from the file to a properly allocated send queue. At his point it transmits the queue synchronized.

Note that the link-layer of the dumpfile is compared with one of the interface that will send the packets using the PcapDevice.DataLink property, and a warning is printed if they are different - it is important that the capture-file link-layer be the same as the adapter's link layer for otherwise the transmission is pointless:

ICaptureDevice device;

    // Create a CaptureFileReaderDevice
    device = new CaptureFileReaderDevice(capFile);
    // Open the device for capturing
catch(Exception e)

Console.Write("Queuing packets...");

// Allocate a new send queue
SendQueue squeue = new SendQueue
Packet packet;

    // Go through all packets in the file and add to the queue 
    while((packet=device.GetNextPacket()) != null )
            Console.WriteLine("Warning: packet buffer too small, "+
                "not all the packets will be sent.");
catch(Exception e)


Console.WriteLine("The following devices are available on this machine:");

int i=0;

var devices = CaptureDeviceList.Instance;

// Print out all available devices
foreach(ICaptureDevice dev in devices)
    Console.WriteLine("{0}) {1}", i, dev.Description);

Console.Write("-- Please choose a device to transmit on: ");
i = int.Parse(Console.ReadLine());
string resp;
if(devices[i].PcapDataLink != device.PcapDataLink)
    Console.Write("Warning: the datalink of the capture"+
        "differs from the one of the selected interface,
        continue? [YES|no]");
    resp = Console.ReadLine().ToLower();
        Console.WriteLine("Canceled by user!");

// Close the device device

// find the network device for sending the packets we read
device = devices[i];

Console.Write("This will transmit all queued packets through"+
    "this device, continue? [YES|no]");
resp = Console.ReadLine().ToLower();
if((resp!="")&&( !resp.StartsWith("y")))
    Console.WriteLine("Canceled by user!");

    Console.Write("Sending packets...");
    int sent = device.SendQueue(squeue, SendQueueTransmitModes.Synchronized);
    if(sent < squeue.CurrentLength)
        Console.WriteLine("An error occurred sending the packets: {0}. "+
            "Only {1} bytes were sent\n", device.LastError, sent);
catch(Exception e)
    Console.WriteLine("Error: "+e.Message );

// Free the queue
Console.WriteLine("-- Queue is disposed.");

// Close the pcap device
Console.WriteLine("-- Device closed.");

Gathering statistics on the network traffic - WinPcap only (Example 11 in the source package)

Adapter statistics are available by calling the ICaptureDevice.Statistics property. The Statistics property is supported by all ICaptureDevice types. WinPcap has a statistics extension that provides statistics callbacks that can be more efficient than retrieving device statistics over and over. WinPcap's statistical engine makes use of the kernel-level packet filter to efficiently classify the incoming packet. You can take a look at the NPF driver internals manual if you want to learn more about the details.

In order to use this feature, the programmer must open an adapter and put it in statistical mode. This can be done by setting the PcapDevice.Mode property. In particular, the PcapDevice.Mode property should be set to CaptureMode.Statistics.

With the statistical mode, making an application that monitors the TCP traffic load is a matter of few lines of code. The following sample shows how to do this:

// Register our handler function to the
// 'winpcap statistics' event
device.OnPcapStatistics +=
    new WinPcap.StatisticsModeEventHandler(device_OnPcapStatistics);

// Open the device for capturing
int readTimeoutMilliseconds = 1000;
device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

// Handle TCP packets only
device.Filter = "tcp";

// Set device to statistics mode
device.Mode = CaptureMode.Statistics;

Console.WriteLine("-- Gathering statistics on \"{0}\",
    hit 'Enter' to stop...", device.Description);

// Start the capturing process

// Wait for 'Enter' from the user.

// Stop the capturing process

// Close the pcap device
Console.WriteLine("Capture stopped, device closed.");

And our event handler will print the statistics:

static int oldSec = 0;
static int oldUsec = 0;

/// <summary>
/// Gets a pcap stat object and calculate bps and pps
/// </summary>
private static void device_OnPcapStatistics(
             object sender, StatisticsModeEventArgs statistics)
    // Calculate the delay in microseconds
    // from the last sample.
    // This value is obtained from the timestamp
    // that's associated with the sample.
    int delay = (statistics.Seconds - oldSec) *
        1000000 - oldUsec + statistics.MicroSeconds;
    /* Get the number of Bits per second */
    long bps = (statistics.RecievedBytes * 8 * 1000000) / delay;
    /*                                  ^        ^
                                     |        |
                                     |        |
                                     |        |
            converts bytes in bits      -----         |
          delay is expressed in microseconds ---------

    // Get the number of Packets per second
    long pps = (statistics.RecievedPackets * 1000000) / delay;

    // Convert the timestamp to readable format
    string ts = statistics.Date.ToLongTimeString();

    // Print Statistics
    Console.WriteLine("{0}: bps={1}, pps={2}",
        ts, bps, pps);

    // store current timestamp
    oldSec = statistics.Seconds;
    oldUsec = statistics.MicroSeconds;

Note that this example is by far more efficient than a program that captures the packets in the traditional way and calculates statistics at the user-level. Statistical mode requires minimum amount of data copies and context switches and therefore the CPU is optimized. Moreover, a very small amount of memory is required. The downside is that if your application uses statistical mode it will only work with WinPcap on Windows.

Queuing packets for background processing - High packet rate capture (Example QueuingPacketsForBackgroundProcessing in the source package)

Packet rates can exceed the rate at which they can be processed by the callback routines. This can occur if the packet processing code is time intensive, such as writing to disk, or if the packet processing code is performing advanced logic. Sometimes it is possible to reduce packet rates by applying bnf filters but in other cases these filters can be complex.

If packet rates only exceed the rate of processing for short periods of time it is possible to simply defer packet processing until periods of less activity. One technique for this is to queue the packets and process them in a background thread as shown in this example.

using System;
using System.Collections.Generic;
using SharpPcap;

namespace QueuingPacketsForBackgroundProcessing
    /// <summary>
    /// Basic capture example showing simple queuing for background processing
    public class MainClass
        /// <summary>
        /// When true the background thread will terminate
        /// </summary>
        /// <param name="args">
        /// A <see cref="System.String"/>
        /// </param>
        private static bool BackgroundThreadStop = false;

        /// <summary>
        /// Object that is used to prevent two threads from accessing
        /// PacketQueue at the same time
        /// </summary>
        /// <param name="args">
        /// A <see cref="System.String"/>
        /// </param>
        private static object QueueLock = new object();

        /// <summary>
        /// The queue that the callback thread puts packets in. Accessed by
        /// the background thread when QueueLock is held
        /// </summary>
        private static List<rawcapture> PacketQueue = new List<rawcapture>();

        /// <summary>
        /// The last time PcapDevice.Statistics() was called on the active device.
        /// Allow periodic display of device statistics
        /// </summary>
        /// <param name="args">
        /// A <see cref="System.String"/>
        /// </param>
        private static DateTime LastStatisticsOutput = DateTime.Now;

        /// <summary>
        /// Interval between PcapDevice.Statistics() output
        /// </summary>
        /// <param name="args">
        /// A <see cref="System.String"/>
        /// </param>
        private static TimeSpan LastStatisticsInterval = new TimeSpan(0, 0, 2);

        /// <summary>
        /// Basic capture example
        /// </summary>
        public static void Main(string[] args)
            // Print SharpPcap version
            string ver = SharpPcap.Version.VersionString;
            Console.WriteLine("SharpPcap {0}", ver);

            // If no device exists, print error
            if(CaptureDeviceList.Instance.Count < 1)
                Console.WriteLine("No device found on this machine");

            Console.WriteLine("The following devices are available on this machine:");

            int i=0;

            // Print out all devices
            foreach(ICaptureDevice dev in CaptureDeviceList.Instance)
                Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);

            Console.Write("-- Please choose a device to capture: ");
            i = int.Parse(Console.ReadLine());

            // start the background thread
            var backgroundThread = new System.Threading.Thread(BackgroundThread);

            ICaptureDevice device = CaptureDeviceList.Instance[i];

            // Register our handler function to the 'packet arrival' event
            device.OnPacketArrival +=
                new PacketArrivalEventHandler(device_OnPacketArrival);

            // Open the device for capturing

            Console.WriteLine("-- Listening on {0}, hit 'Enter' to stop...",

            // Start the capturing process

            // Wait for 'Enter' from the user. We pause here until being asked to
            // be terminated

            // Stop the capturing process

            Console.WriteLine("-- Capture stopped.");

            // ask the background thread to shut down
            BackgroundThreadStop = true;

            // wait for the background thread to terminate

            // Print out the device statistics

            // Close the pcap device

        /// <summary>
        /// Prints the time and length of each received packet
        /// </summary>
        private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
            // print out periodic statistics about this device
            var Now = DateTime.Now; // cache 'DateTime.Now' for minor reduction in cpu overhead
            var interval = Now - LastStatisticsOutput;
            if(interval > LastStatisticsInterval)
                Console.WriteLine("device_OnPacketArrival: " + ((ICaptureDevice)e.Device).Statistics());
                LastStatisticsOutput = Now;

            // lock QueueLock to prevent multiple threads accessing PacketQueue at
            // the same time

        /// <summary>
        /// Checks for queued packets. If any exist it locks the QueueLock, saves a
        /// reference of the current queue for itself, puts a new queue back into
        /// place into PacketQueue and unlocks QueueLock. This is a minimal amount of
        /// work done while the queue is locked.
        /// The background thread can then process queue that it saved without holding
        /// the queue lock.
        /// </summary>
        private static void BackgroundThread()
                bool shouldSleep = true;

                    if(PacketQueue.Count != 0)
                        shouldSleep = false;

                else // should process the queue
                    List<RawCapture> ourQueue;
                        // swap queues, giving the capture callback a new one
                        ourQueue = PacketQueue;
                        PacketQueue = new List<RawCapture>();

                    Console.WriteLine("BackgroundThread: ourQueue.Count is {0}", ourQueue.Count);

                    foreach(var packet in ourQueue)
                        var time = packet.Timeval.Date;
                        var len = packet.Data.Length;
                        Console.WriteLine("BackgroundThread: {0}:{1}:{2},{3} Len={4}",
                            time.Hour, time.Minute, time.Second, time.Millisecond, len);

                    // Here is where we can process our packets freely without
                    // holding off packet capture.
                    // NOTE: If the incoming packet rate is greater than
                    //       the packet processing rate these queues will grow
                    //       to enormous sizes. Packets should be dropped in these
                    //       cases



  • 2014-May-2
    • Corrected some mistakes in the examples that users had reported in the comments section.
    • Removed the link to, Tamir's site appears to have gone away.
    • Adjusted examples to reflect the change from per-packet type GetEncapculated() methods to the Packet.Extract() approach.
  • 2011-Sep-13
    • Updates for new classes for reading and writing capture files, CaptureFileWriterDevice and CaptureFileReaderDevice
  • 2011-Feb-24
    • Separate out Packet.Net packet types from description of SharpPcap
    • Rename PacketDotNet.RawPacket to SharpPcap.RawCapture
    • Shorten the document length
  • 2011-Feb-01
    • Updated for SharpPcap v3.5 API changes
  • 2010-Nov-07
    • Updated for SharpPcap v3.x
    • Added queuing example for high packet rates
  • 2010-Jan-27
    • Updated for the current version of SharpPcap, v2.4.0.
  • 2005-Nov-27
    • Initial version posted.


This article, along with any associated source code and files, is licensed under The Mozilla Public License 1.1 (MPL 1.1)


About the Authors

Tamir Gal
Software Developer
Israel Israel
Works as a Network Engineer for a leading networking company.

Chris Morgan_
United States United States
Entrepreneur and product developer with a wide range of technical and business experience.

You may also be interested in...

Comments and Discussions

QuestionHow can I send/receive a packet to localhost? Pin
Member 1160784225-Nov-15 21:05
memberMember 1160784225-Nov-15 21:05 
QuestionPrivileged access to run app with SharpPcap Pin
Member 1214306716-Nov-15 2:48
memberMember 1214306716-Nov-15 2:48 
QuestionAllocating SharpPcap SendQueue Pin
op103126-Oct-15 12:37
memberop103126-Oct-15 12:37 
GeneralMy vote of 5 Pin
pierrecss26-Sep-15 16:30
memberpierrecss26-Sep-15 16:30 
QuestionRecognize TCP CLOSE in device_OnPacketArrival Pin
Maria Bagheri19-Jun-15 21:30
memberMaria Bagheri19-Jun-15 21:30 
Questionlist all servers pppoe active Pin
coopermine230-Mar-15 12:48
membercoopermine230-Mar-15 12:48 
Questionhow do I get device ip addr via sharppcap4.2? Pin
Member 1132652421-Dec-14 16:11
groupMember 1132652421-Dec-14 16:11 
QuestionDNSSEC support? Pin
Member 1118586328-Oct-14 0:26
memberMember 1118586328-Oct-14 0:26 
Questionproblems with sleep mode Pin
meitar1221-Jul-14 7:09
membermeitar1221-Jul-14 7:09 
QuestionHow to print the data of TCP package ? Pin
Member 109221323-Jul-14 3:28
memberMember 109221323-Jul-14 3:28 
QuestionGreat Stuff Pin
Alois Kraus25-Jun-14 11:39
memberAlois Kraus25-Jun-14 11:39 
QuestionTimestamp in TCP package In Windows Pin
jatinchandarana24-Apr-14 6:49
memberjatinchandarana24-Apr-14 6:49 
QuestionCaptureDeviceList not compiling Pin
Member 999427724-Mar-14 23:25
memberMember 999427724-Mar-14 23:25 
AnswerRe: CaptureDeviceList not compiling Pin
Stefan Ossendorf18-Dec-14 11:01
memberStefan Ossendorf18-Dec-14 11:01 
QuestionSending UDP frame Pin
Stephan Stricker31-Jan-14 8:28
memberStephan Stricker31-Jan-14 8:28 
QuestionPromiscuous mode. Not function and using Wireshark yes Pin
Member 476126823-Jan-14 5:11
memberMember 476126823-Jan-14 5:11 
QuestionCan I send packets to localhost? Pin
geniaz110-Jul-13 2:47
membergeniaz110-Jul-13 2:47 
QuestionCan I use sharppcap to capture packets from more than one device at one time Pin
shiyanscree27-Jun-13 23:10
membershiyanscree27-Jun-13 23:10 
QuestionSimply fantastic explanation Pin
CarlosAlbertoEstrada10-Jun-13 13:38
memberCarlosAlbertoEstrada10-Jun-13 13:38 
GeneralMy vote of 5 Pin
The Dogor16-Jan-13 6:42
memberThe Dogor16-Jan-13 6:42 
QuestionAbout WinPcap Pin
takepatience25-Dec-12 4:15
membertakepatience25-Dec-12 4:15 
AnswerRe: About WinPcap Pin
chmorgan3-May-14 11:05
memberchmorgan3-May-14 11:05 
QuestionChange IP packet properties Pin
serob24-Sep-12 7:26
memberserob24-Sep-12 7:26 
AnswerRe: Change IP packet properties Pin
chmorgan3-May-14 12:29
memberchmorgan3-May-14 12:29 
SuggestionAdding a "Tag" field to ICaptureDevice or PcapDevice Pin
Erik Turner8-Aug-12 11:13
memberErik Turner8-Aug-12 11:13 
GeneralRe: Adding a "Tag" field to ICaptureDevice or PcapDevice Pin
chmorgan3-May-14 12:32
memberchmorgan3-May-14 12:32 
QuestionHaving Problem in example 3 Pin
Yashashree Bendale27-Feb-12 8:36
memberYashashree Bendale27-Feb-12 8:36 
AnswerRe: Having Problem in example 3 Pin
Member 1021627318-Aug-13 1:30
memberMember 1021627318-Aug-13 1:30 
Question"Response" Time from Sending to Receiving Pin
Emperor94417-Feb-12 14:12
memberEmperor94417-Feb-12 14:12 
AnswerRe: "Response" Time from Sending to Receiving Pin
chmorgan17-Feb-12 14:37
memberchmorgan17-Feb-12 14:37 
QuestionRe: "Response" Time from Sending to Receiving Pin
Emperor94421-Feb-12 8:52
memberEmperor94421-Feb-12 8:52 
AnswerRe: "Response" Time from Sending to Receiving Pin
Emperor94421-Feb-12 9:31
memberEmperor94421-Feb-12 9:31 
GeneralRe: "Response" Time from Sending to Receiving Pin
chmorgan21-Feb-12 9:34
memberchmorgan21-Feb-12 9:34 
GeneralRe: "Response" Time ----- Code & Output Sample Pin
Emperor94421-Feb-12 13:04
memberEmperor94421-Feb-12 13:04 
AnswerRe: "Response" Time from Sending to Receiving - Final Solution Pin
Emperor94422-Feb-12 10:46
memberEmperor94422-Feb-12 10:46 
QuestionHow to write to a new pcap file after constructing my own packets? Pin
acui014-Jan-12 6:16
memberacui014-Jan-12 6:16 
QuestionHow to construct packets and write to a new pcap file? Pin
acui014-Jan-12 6:15
memberacui014-Jan-12 6:15 
Questionabout icmp Pin
Kerisnaity15-Dec-11 17:04
memberKerisnaity15-Dec-11 17:04 
## i am poor at english

i practice send icmp-packet..

but it does not work well..

i send request-packet.. and capture packet by wireshark..

but only request-packet, can't receive reply-packet


ping test 'google'

byte[] icmp = new byte[43];
        #region Init
        //Dst Mac
        icmp[0] = (byte)0x00;
        icmp[1] = (byte)0x30;
        icmp[2] = (byte)0x18;
        icmp[3] = (byte)0xA1;
        icmp[4] = (byte)0x61;
        icmp[5] = (byte)0x73;
        //Src Mac
        icmp[6] = (byte)0x;
        icmp[7] = (byte)0x;
        icmp[8] = (byte)0x;
        icmp[9] = (byte)0x;
        icmp[10] = (byte)0x;
        icmp[11] = (byte)0x;
        //Ether Type
        icmp[12] = (byte)0x08;
        icmp[13] = (byte)0x00;
        //Ver + Header Length
        icmp[14] = (byte)0x45;
        //Type of Service
        icmp[15] = (byte)0x00;
        //Total Length
        icmp[16] = (byte)0x00;
        icmp[17] = (byte)0x3C;
        icmp[18] = (byte)0x0C;
        icmp[19] = (byte)0x39;
        icmp[20] = (byte)0x00;
        //Fragment offset
        icmp[21] = (byte)0x00;
        icmp[22] = (byte)0x80;
        icmp[23] = (byte)0x01;
        //Header Checksum
        icmp[24] = (byte)0x2F;
        icmp[25] = (byte)0x6C;
        //Src IP
        icmp[26] = (byte)0xB6;
        icmp[27] = (byte)0xFC;
        icmp[28] = (byte)0xDE;
        icmp[29] = (byte)0x3A;
        //Dst IP
        icmp[30] = (byte)0x4A;
        icmp[31] = (byte)0x7D;
        icmp[32] = (byte)0x1F;
        icmp[33] = (byte)0x68;
        //ICMP Type
        icmp[34] = (byte)0x08;
        //ICMP Code
        icmp[35] = (byte)0x00;
        //ICMP Checksum
        icmp[36] = (byte)0x4D;
        icmp[37] = (byte)0x54;
        //ICMP ID
        icmp[38] = (byte)0x00;
        icmp[39] = (byte)0x01;
        //ICMP Sequence
        icmp[40] = (byte)0x00;
        icmp[41] = (byte)0x09;
        //ICMP Data
        icmp[42] = (byte)0x61;


        device.Open(DeviceMode.Promiscuous, 1000);

Questionabout Promiscuous Mode Pin
Member 847274012-Dec-11 1:34
memberMember 847274012-Dec-11 1:34 
AnswerRe: about Promiscuous Mode Pin
Serge Wenger Work12-Dec-11 20:46
memberSerge Wenger Work12-Dec-11 20:46 
Questionmonitor http transfer and edit it Pin
hamid_m25-Nov-11 1:22
memberhamid_m25-Nov-11 1:22 
AnswerRe: monitor http transfer and edit it Pin
Narayanan Sankaranarayanan15-Dec-11 8:54
memberNarayanan Sankaranarayanan15-Dec-11 8:54 
GeneralRe: monitor http transfer and edit it Pin
chmorgan15-Dec-11 9:01
memberchmorgan15-Dec-11 9:01 
QuestionProblem in opening ICapture device Pin
Hazame14-Nov-11 23:21
memberHazame14-Nov-11 23:21 
AnswerRe: Problem in opening ICapture device Pin
pianocomposer13-Aug-12 9:22
memberpianocomposer13-Aug-12 9:22 
GeneralRe: Problem in opening ICapture device Pin
chmorgan3-May-14 12:30
memberchmorgan3-May-14 12:30 
QuestionPacket Reconstruction Pin
nonintrusive31-Oct-11 2:36
membernonintrusive31-Oct-11 2:36 
AnswerRe: Packet Reconstruction Pin
chmorgan31-Oct-11 5:44
memberchmorgan31-Oct-11 5:44 
GeneralMy vote of 5 Pin
lixiaohua01292-Oct-11 4:30
memberlixiaohua01292-Oct-11 4:30 
GeneralMy vote of 5 Pin
Hari Om Prakash Sharma14-Sep-11 21:34
memberHari Om Prakash Sharma14-Sep-11 21:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.151126.1 | Last Updated 5 May 2014
Article Copyright 2005 by Tamir Gal, Chris Morgan_
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid