I'm using SharpPcap to dump packets to a .pcap file. My problem is, that it's working to slow to capture any amount of network traffic and I run out of memory eventually. How can i speed up the file writing process?
Here is the code I'm using:
private void WriteToPCAPThread(object o)
{
this.WritePcapThreadDone.Reset();
string captureFileName = (string)o;
CaptureFileWriterDevice captureFileWriter = new CaptureFileWriterDevice(this.device, captureFileName);
captureFileWriter.Open();
RawCapture packet;
bool success;
while (this.capturing)
{
success = this.captures.TryDequeue(out packet);
if (success)
{
captureFileWriter.Write(packet);
}
else
{
// Queue emptied
Thread.Sleep(50);
}
}
}
Thanks in advance for any ideas.
I ended up writing my own StreamWriter. Now I get 100% performance out of my SSD.
public PcapStream
{
private Stream BaseStream;
public PcapStream(Stream BaseStream)
{
this.BaseStream=BaseStream;
}
public void Write(RawCapture packet)
{
byte[] arr = new byte[packet.Data.Length + 16];
byte[] sec = BitConverter.GetBytes((uint)packet.Timeval.Seconds);
byte[] msec = BitConverter.GetBytes((uint)packet.Timeval.MicroSeconds);
byte[] incllen = BitConverter.GetBytes((uint)packet.Data.Length);
byte[] origlen = BitConverter.GetBytes((uint)packet.Data.Length);
Array.Copy(sec, arr, sec.Length);
int offset = sec.Length;
Array.Copy(msec, 0, arr, offset, msec.Length);
offset += msec.Length;
Array.Copy(incllen, 0, arr, offset, incllen.Length);
offset += incllen.Length;
Array.Copy(origlen, 0, arr, offset, origlen.Length);
offset += origlen.Length;
Array.Copy(packet.Data, 0, arr, offset, packet.Data.Length);
BaseStream.Write(arr, 0, arr.Length);
}