pcap-sharp
Tuesday, February 27th, 2007Purely out of boredom (even though I have plenty of homework to do) I decided to hack out a managed wrapper around libpcap. Though it’s only a few hours later, the implementation is complete enough to read packets off the wire. Here is a quick example of how it could be used:
using System;
using PcapSharp;
public class MainClass {
public static void Main(string[] args) {
Console.WriteLine("Using {0}", Pcap.LibraryVersion);
PcapHandle handle = Pcap.OpenLive("eth2", short.MaxValue, true, 5000);
handle.Loop(-1, delegate(Packet p) {
Console.WriteLine("At {0}, recieved a {1}-byte packet.", p.Time, p.RealLength);
Console.Write(" The first five bytes are:");
for (int i = 0; i < 5; i++)
Console.Write(" {0}", p[i]);
Console.WriteLine();
});
}
}
Which does something like this:
# ./pcaptest.exe Using libpcap version 0.9.5 At 2/27/2007 9:26:49 AM, recieved a 60-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:49 AM, recieved a 60-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:49 AM, recieved a 60-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:49 AM, recieved a 60-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:49 AM, recieved a 60-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:50 AM, recieved a 243-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:50 AM, recieved a 60-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:50 AM, recieved a 60-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:50 AM, recieved a 62-byte packet. The first five bytes are: 0 20 94 34 48 At 2/27/2007 9:26:50 AM, recieved a 60-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:50 AM, recieved a 161-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:50 AM, recieved a 60-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:50 AM, recieved a 60-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:51 AM, recieved a 60-byte packet. The first five bytes are: 255 255 255 255 255 At 2/27/2007 9:26:51 AM, recieved a 60-byte packet. The first five bytes are: 255 255 255 255 255 ...
The library is in my public Subversion repository (svn co https://layla.chrishowie.com/svn/pcap-sharp) and is available under the terms of the MIT license.