The Winpcap library is an excellent method of reading and writing data packet, but it is not so easy to interface to from .NET. Thus this design tip uses a code wrapper from the Code Project [Click here]. The solution and demo of this example is at:
[Click here to download of the solution]
Video: [Click here for a demo]
and uses the following code:
using System; using Tamir.IPLib; using Tamir.IPLib.Packets;
namespace NapierCapture { public class CapturePackets { public static void Main (string[] args) { PcapDeviceList getNetConnections = SharpPcap.GetAllDevices(); // network connection 1 (change as required) NetworkDevice netConn = (NetworkDevice)getNetConnections[1]; PcapDevice device = netConn; // Define packet handler device.PcapOnPacketArrival += new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival); //Open the device for capturing //true -- means promiscuous mode //1000 -- means a read wait of 1000ms device.PcapOpen( true , 1000); Console.WriteLine("Network connection: {0}", device.PcapDescription); //Start the capturing process device.PcapStartCapture(); Console.Write("Press any <RETURN> to exit"); Console.Read();
device.PcapStopCapture(); device.PcapClose(); }
private static void device_PcapOnPacketArrival( object sender, Packet 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); } } }
|
A sample run shows data packets and their lengths:
13:17:56,990 Len=695
13:17:57,66 Len=288
13:17:57,68 Len=694
13:18:4,363 Len=319
13:18:4,364 Len=373
13:18:4,364 Len=371
13:18:4,365 Len=375
13:18:4,366 Len=367
|
Most of the captured traffic, in this case is backgroun traffic with small data packets. If we want to capture only IP and TCP then a filter can be setup:
device.PcapOpen( true , 1000); Console.WriteLine("Network connection: {0}", device.PcapDescription); string filter = "ip and tcp"; //Associate the filter with this capture device.PcapSetFilter( filter ); //Start the capturing process device.PcapStartCapture();
|
To capture just ICMP packet (such as from PING and TRACERT) we can modify the filter with:
string filter = "icmp";
Thus when we ping a node, such as:
Ping 192.168.1.102
The result is something like:
13:40:47,761 Len=74
13:40:48,756 Len=74
13:40:48,759 Len=74
13:40:49,757 Len=74
13:40:49,760 Len=74
13:40:50,757 Len=74
13:40:50,760 Len=74
|
|
|