如何使用SharpPcap快速转储数据包

How to use SharpPcap to dump packets fast

我正在使用 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);
            }
        }
    }

提前感谢您的任何想法。

我最终编写了自己的 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);
    }