我使用SharpPcap将数据包转储到.pcap文件。我的问题是,它正在努力减慢捕获任何数量的网络流量,并最终耗尽内存。 如何加快文件写入过程?
以下是我使用的代码:
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);
}
}
}
提前感谢任何想法。
答案 0 :(得分:0)
我最终编写了自己的StreamWriter。现在我的SSD获得了100%的性能。
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);
}