C# full managed implementation Pcap/PcapNG file format
PM> Install-Package Haukcode.PcapngUtils
The implementation of these formats is made by wrapping unmanaged WinPcap library. I added the implementation of both formats in a fully managed C #.
public void OpenPcapFile(string filename,CancellationToken token) { using (var reader = new PcapReader(filename)) { reader.OnReadPacketEvent += reader_OnReadPacketEvent; reader.ReadPackets(token); reader.OnReadPacketEvent -= reader_OnReadPacketEvent; } }
void reader_OnReadPacketEvent(object context, IPacket packet) { Console.WriteLine(string.Format("Packet received {0}.{1}",packet.Seconds, packet.Microseconds )); }
Better solutions, library can recognize the file format,public void OpenPcapNGFile(string filename,bool swapBytes,CancellationToken token) { using (var reader = new PcapNGReader("test.pcap",swapBytes)) { reader.OnReadPacketEvent += reader_OnReadPacketEvent; reader.ReadPackets(token); reader.OnReadPacketEvent -= reader_OnReadPacketEvent; } }
void reader_OnReadPacketEvent(object context, IPacket packet) { Console.WriteLine(string.Format("Packet received {0}.{1}",packet.Seconds, packet.Microseconds )); }
public void OpenPcapORPcapNFFile(string filename,CancellationToken token) { using (var reader = IReaderFactory.GetReader(filename)) { reader.OnReadPacketEvent += reader_OnReadPacketEvent; reader.ReadPackets(token); reader.OnReadPacketEvent -= reader_OnReadPacketEvent; } }
void reader_OnReadPacketEvent(object context, IPacket packet) { Console.WriteLine(string.Format("Packet received {0}.{1}",packet.Seconds, packet.Microseconds )); }
public void CloneFile(string inputFileName, string outputFileName, CancellationToken token)
{
using (var reader = IReaderFactory.GetReader(inputFileName))
{
using (var writer = new PcapWriter(outputFileName))
{
CommonDelegates.ReadPacketEventDelegate handler = (obj, packet) =>
{
writer.WritePacket(packet);
};
reader.OnReadPacketEvent += handler;
reader.ReadPackets(token);
reader.OnReadPacketEvent -= handler;
}
}
}
public void CloneFile(string inputFileName, string outputFileName, CancellationToken token)
{
using (var reader = IReaderFactory.GetReader(inputFileName))
{
using (var writer = new PcapNGWriter(outputFileName))
{
CommonDelegates.ReadPacketEventDelegate handler = (obj, packet) =>
{
writer.WritePacket(packet);
};
reader.OnReadPacketEvent += handler;
reader.ReadPackets(token);
reader.OnReadPacketEvent -= handler;
}
}
}