Click here to Skip to main content
6,822,123 members and growing! (16,303 online)
Email Password   helpLost your password?
General Programming » Internet / Network » Network     Intermediate License: The Mozilla Public License 1.1 (MPL 1.1)

SharpPcap - A Packet Capture Framework for .NET

By Tamir Gal

A framework for capturing, injecting and analyzing network packets for .NET applications based on the WinPcap packet capture driver
C#, Windows, .NET, Visual-Studio, Dev
Posted:27 Nov 2005
Updated:28 Jan 2010
Views:175,954
Bookmarked:229 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
108 votes for this article.
Popularity: 9.90 Rating: 4.87 out of 5
1 vote, 0.9%
1

2
2 votes, 1.9%
3
3 votes, 2.8%
4
102 votes, 94.4%
5
[A .NET sniffer application written with SharpPcap]

Introduction

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 give you a detailed programming tutorial on how to use it.

Background

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 first project is a great ethereal .NET clone that lets you capture and analyze numerous types of protocol packets. However, a few issues with this project make it almost impossible to be shared among other .NET applications. Firstly, the author did not provide any generic API for capturing packets that can be used by other .NET applications. He didn't separate his UI code and his analyzing and capturing code, making his capturing code depend on the GUI classes such as ListView to operate. Secondly, for some reason the author chose to re-implement some of WinPcap's functions in C# by himself rather than just wrapping them. This means that his application can't take advantage of the new WinPcap versions since he hard coded a certain version of WinPcap in his application.

The second and the third articles are nice starts for wrapper projects for WinPcap, however they didn't provide some important WinPcap features such as handling offline pcap files and applying kernel-level packet filters, and most importantly they provide no parser classes for analyzing protocol packets. Both projects didn't post their library source code together with the article in order to let other people extend their work and add new features and new packet parser classes.

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. Development is active and ongoing in the 2.x series.

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
    • Setting the kernel buffer size
    • Injecting packets using send queues
    • Collecting network statistics on a given network interface
  • Enumerating and showing details about the physical network interface on a Windows machine.
  • Capturing low-level network packets going through a given interface.
  • Analyzing and parsing the following protocols: Ethernet, ARP, IP (IPv4 and IPv6), TCP, UDP, ICMP, IGMP.
  • Injecting low-level network packets on a given interface.
  • Handling (reading and writing) offline packet capture files.
  • Retrieving adapter statistics on packets received vs. dropped

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

SharpPcap Tutorial: A Step by Step Guide to Using SharpPcap

Examples can be found in the Examples/ directory of the source package.

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 handler (Example 4)
  4. Filtering the traffic (Example 5)
  5. Interpreting the packets
  6. Handling offline dump files
  7. Sending packets
  8. Gathering statistics on the network traffic

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, LivePcapDeviceList for this purpose. The class is a singleton instance that holds a cached list of network adapters of type LivePcapDevice. 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
LivePcapDeviceList devices = LivePcapDeviceList.Instance;

// If no devices were found print an error
if(devices.Count < 1)
{
    Console.WriteLine("No devices were found on this machine");
    return;
}
 
Console.WriteLine("\nThe following devices are available on this machine:");
Console.WriteLine("----------------------------------------------------\n");


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

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

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

c:\sharppcap\Examples\Example1.IfList\bin\Debug>Example1.IfList.exe
SharpPcap 2.3.0.0, 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
Addresses:
Addr:      fe80::b444:92d8:c882:8227
Netmask:
Broadaddr:

Addresses:
Addr:      10.0.2.15
Netmask:   255.255.255.0
Broadaddr: 255.255.255.255

Addresses:
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, 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 PcapDevice:

// Extract a device from the list 
PcapDevice 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...",
    device.Description);

// Start the capturing process 
device.StartCapture();

// Wait for 'Enter' from the user. 
Console.ReadLine();
 
// Stop the capturing process 
device.StopCapture();

// Close the pcap device
device.Close();

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

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. When using Capture(int packetCount) it is possible to pass a SharpPcap.INFINITE value to keep capturing forever.

Both of these functions require that an event handler for processing packets registered prior to calling them. This event handler is invoked by PcapDevice for every new packet coming from the network and receives the sender object that invoked this handler (i.e. the PcapDevice 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 PcapDevice; 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 PcapDevice.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 
PcapDevice device = devices[i];

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

Console.WriteLine();
Console.WriteLine("-- Listening on {0}...",
    device.Description);
 
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 
device.Close();
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 function SetFilter() associates a filter with a capture adapter. Once SetFilter() is called, 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 PcapDevice 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.SetFilter( filter );
 
Console.WriteLine();
Console.WriteLine
  ("-- The following tcpdump filter will be applied: \"{0}\"", 
  filter);
Console.WriteLine
  ("-- Listening on {0}, hit 'Enter' to stop...",
  device.Description);
 
// Start capture packets
device.Capture( SharpPcap.INFINITE );
 
// Close the pcap device 
// (Note: this line will never be called since 
// we're capturing infinite number of packets 
device.Close();

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 packet)
{            
    if(packet is TCPPacket)
    {                
        DateTime time = packet.Timeval.Date;
        int len = packet.PcapHeader.len;
 
        TCPPacket tcp = (TCPPacket)packet;
        string srcIp = tcp.SourceAddress;
        string dstIp = tcp.DestinationAddress;
        int srcPort = tcp.SourcePort;
        int dstPort = tcp.DestinationPort;
 
        Console.WriteLine("{0}:{1}:{2},
            {3} Len={4} {5}:{6} -> {7}:{8}", 
            time.Hour, time.Minute, time.Second, 
            time.Millisecond, len, srcIp, srcPort, 
            dstIp, dstPort);
    }
}

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 these analyzing classes can be found under the SharpPcap.Packets namespace.

As you can see, in our packet handler we first do a check to verify that the Packet object received from the PcapDevice is of type TCPPacet, and only then we cast it to a TCPPacet. This check is not really needed if we set the appropriate filter using the SetFilter() function, however we use it here as a good practice.

The TCPPacket is a subclass of the IPPacket class (since TCP runs on top of IP), so all TCP/IP fields are accessible using TCPPacet's properties. In the above example, we extract the TCP and IP values from the TCPPacket class and print them on the screen (of course, the TCPPacket class contains additional info such as TCP flags and sequence number fields, which are not shown in this example). The resulting output is something like this:

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 66.102.7.147:80 -> 10.21.98.21:43501
1:18:17,675 Len=80 10.21.98.21:43501 -> 66.102.7.147:80
1:18:17,919 Len=54 66.102.7.147:80 -> 10.21.98.21:43501

Each of the final three lines represents a different packet.

Handling Offline Dump Files (Example 8 in the Source Package)

In this section, we are going to learn how to handle packet capture to a file (dump to file). Libpcap/WinPcap offer built-in functions for saving network traffic to a file and to read the content of dumps - this section will teach you how to accomplish this with SharpPcap. The format for dump files is the libpcap one. This format contains the data of the captured packets in binary form and is a standard widely used by many network tools including wireshark, windump, tcpdump and snort. Therefore, any dump file we create using SharpPcap can be opened with any of the above tools and others and files created by these tools can be opened by SharpPcap.

Saving Packets to a Dump File

First of all, let's see how to write packets in libpcap file format. The following example captures the packets from the selected interface and saves them on a file whose name is provided by the user:

Console.Write("-- Please enter the output file name: ");
string capFile = Console.ReadLine();
 
PcapDevice device = LivePcapDeviceList.Instance[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);

// Open or create a capture output file 
device.DumpOpen( capFile );
 
Console.WriteLine();
Console.WriteLine
    ("-- Listening on {0}, hit 'Ctrl-C' to exit...",
    device.Description);

// Start capture 'INFINTE' number of packets 
device.Capture( SharpPcap.INFINITE );
 
// Close the pcap device 
// (Note: this line will never be called since
// we're capturing infinite number of packets
device.Close();

And here is the packet handler that will dump each received packet to the file:

/// <SUMMARY> 
/// Dumps each received packet to a pcap file 
/// </SUMMARY> 
private static void device_OnPacketArrival(
                        object sender, CaptureEventArgs packet)
{                        
    PcapDevice device = (PcapDevice)sender;
    // if device has a dump file opened 
    if( device.DumpOpened )
    {
        // dump the packet to the file 
        device.PcapDump( packet );
        Console.WriteLine("Packet dumped to file.");
    }
}

As you can see, the structure of the program is very similar to the ones we have seen in the previous sections. The differences are:

  • The call to device.DumpOpen( capFile ) is issued once the interface is opened. This call opens a dump file and associates it with the interface.
  • The packets are written to this file with the device.PcapDump( packet ) call in the packet handler. Note the use of the sender object parameter passed to the packet handler callback which is casted to a PcapDevice.

Reading Packets from a Dump File

Now that we have a dump file available, we can try to read its content. The following code opens a WinPcap/libpcap dump file and displays every packet contained in the file. The SharpPcap.OfflinePcapDevice( capFile ) class is a PcapDevice object which represents the offline capture file that we read, then the usual OnPacketArrival event is used to sequence through the packets. As you can see, reading packets from an offline capture is nearly identical to receiving them from a physical interface:

Console.Write("-- Please enter an input capture file name: ");
string capFile = Console.ReadLine();
 
PcapDevice device;
 
try 
{
    // Get an offline file pcap device 
    device = new OfflinePcapDevice( capFile );
    // Open the device for capturing 
    device.Open();
} 
catch(Exception e)
{
    Console.WriteLine(e.Message);
    return;
}
 
// Register our handler function to the 'packet arrival' event 
device.OnPacketArrival += 
  new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
 
Console.WriteLine();
Console.WriteLine
    ("-- Capturing from '{0}', hit 'Ctrl-C' to exit...",
    capFile);

// Start capture 'INFINTE' number of packets 
// This method will return when EOF reached. 
device.Capture( SharpPcap.INFINITE );

// Close the pcap device 
device.Close();
Console.WriteLine("-- End of file reached.");

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 net as is, without any manipulation. This means that the application has to create the correct protocol headers in order to send something meaningful:

// Open the device 
device.Open();
 
// Generate a random packet 
byte[] bytes = GetRandomPacket();
 
try 
{
    // 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 
device.Close();
Console.WriteLine("-- Device closed.");

Send Queues - WinPcap Specific Extension (Example 11 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 PcapDevice.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 PcapDevice.SendQueue() is more efficient than performing a series of PcapDevice.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 OfflinePcapDevice(), 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:

PcapDevice device;
 
try 
{
    // Get an offline file pcap device 
    device = new OfflinePcapDevice( capFile );
    // Open the device for capturing 
    device.Open();
} 
catch(Exception e)
{
    Console.WriteLine(e.Message);
    return;
}
 
Console.Write("Queueing packets...");
 
// Allocate a new send queue 
SendQueue squeue = new SendQueue
    ( (int)((OfflinePcapDevice)device).PcapFileSize );
Packet packet;
 
try 
{
  // Go through all packets in the file and add to the queue 
  while( (packet=device.GetNextPacket()) != null )
  {
     if( !squeue.Add( packet ) )
     {
        Console.WriteLine("Warning: packet buffer too small, "+
                            "not all the packets will be sent.");
        break;
     }
  }
}
catch(Exception e)
{
    Console.WriteLine(e.Message);
    return;
}

Console.WriteLine("OK");
 
Console.WriteLine();
Console.WriteLine("The following devices are available on this machine:");
Console.WriteLine("----------------------------------------------------");
Console.WriteLine();
 
int i=0;
 
var devices = LivePcapDeviceList.Instance;

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

Console.WriteLine();
Console.Write("-- Please choose a device to transmit on: ");
i = int.Parse( Console.ReadLine() );
devices[i].Open();
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();
 
    if((resp!="")&&( !resp.StartsWith("y")))
    {
        Console.WriteLine("Cancelled by user!");
        devices[i].Close();
        return;
    }
}

// Close the offline device
device.Close();

// 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("Cancelled by user!");
    return;
}

try 
{
    Console.Write("Sending packets...");
    int sent = device.SendQueue( squeue, SendQueueTransmitModes.Synchronized );
    Console.WriteLine("Done!");
    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 
squeue.Dispose();
Console.WriteLine("-- Queue is disposed.");
// Close the pcap device
device.Close();
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 PcapDevice.Statistics() method but WinPcap has a statistics extension that provides statistics callbacks. 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 SharpPcap.StatisticsEventHandler( 
                         device_OnPcapStatistics );

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

// Handle TCP packets only 
device.SetFilter( "tcp" );

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

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

// Start the capturing process 
device.StartCapture();

// Wait for 'Enter' from the user. 
Console.ReadLine();
 
// Stop the capturing process 
device.StopCapture();
 
// Close the pcap device 
device.Close();
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.

References

History

  • 2010-Jan-27
    • Updated for the current version of SharpPcap, v2.4.0
  • 2005-Nov-27
    • Initial version posted

License

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

About the Author

Tamir Gal


Member
Works as a Network Engineer for a leading networking company.
Occupation: Software Developer
Location: Israel Israel

Other popular Internet / Network articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 226 to 250 of 264 (Total in Forum: 264) (Refresh)FirstPrevNext
QuestionGathering Statistics on the network traffic PinmemberNeO[LiG]1:08 25 Jul '06  
GeneralUrgent Help needed on Capturing Emails Pinmembermishu222217:58 11 Jul '06  
GeneralHow fast can it go? PinmemberMark Buchanan5:08 21 Jun '06  
GeneralRe: How fast can it go? PinmemberTamir Gal13:32 23 Jun '06  
GeneralPcapDumpClose PinmemberSerge Wenger Work5:54 15 Jun '06  
GeneralProcess ID PinmemberStefanKittel7:33 4 Jun '06  
GeneralRe: Process ID [modified] PinmemberTamir Gal20:48 4 Jun '06  
GeneralRe: Process ID PinmemberTamir Gal4:06 3 Jul '06  
GeneralListening packets on other host/PC PinmemberInsphere Technology18:21 26 Apr '06  
AnswerRe: Listening packets on other host/PC PinmemberSerge Wenger Work20:36 26 Apr '06  
GeneralRe: Listening packets on other host/PC PinmemberInsphere Technology20:44 26 Apr '06  
Generalhow can i access pointer to sockaddr PinmemberDardirDotNet12:10 22 Apr '06  
Generalpcap_findalldevs_ex PinmemberDardirDotNet8:49 22 Apr '06  
Generalwinpcap question PinmemberChris TB7:37 10 Apr '06  
GeneralRe: winpcap question PinmemberChris TB7:56 10 Apr '06  
GeneralRe: winpcap question PinmemberTamir Gal20:50 4 Jun '06  
QuestionPcapStartCapture( ) problem when not running from IDE? Pinmemberwork2gs2:37 21 Mar '06  
AnswerRe: PcapStartCapture( ) problem when not running from IDE? PinmemberTamir Gal3:42 21 Mar '06  
GeneralRe: PcapStartCapture( ) problem when not running from IDE? Pinmemberwork2gs5:24 21 Mar '06  
GeneralGreat Work. What licence is the code released under? Pinmembermaczor_aus13:35 9 Mar '06  
GeneralRe: Great Work. What licence is the code released under? PinmemberTamir Gal4:52 10 Mar '06  
QuestionGreat~ But how to identify the high level protocol? Pinmemberflair2:48 3 Mar '06  
AnswerRe: Great~ But how to identify the high level protocol? PinmemberTamir Gal3:08 3 Mar '06  
QuestionRe: Great~ But how to identify the high level protocol? Pinmemberflair3:23 3 Mar '06  
GeneralRe: Great~ But how to identify the high level protocol? Pinmemberwuyanbo2:48 11 Jul '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 28 Jan 2010
Editor: Deeksha Shenoy
Copyright 2005 by Tamir Gal
Everything else Copyright © CodeProject, 1999-2010
Web17 | Advertise on the Code Project