重新启动部分代码? SharpPCap的问题

时间:2018-07-31 12:30:49

标签: c# tcp timer packet-sniffers sharppcap

我正在运行一个用于游戏的网络嗅探器,并试图捕获某些流量,但遇到的问题很可能是SharpPcap遇到多个TCP连接问题(例如,当我打开或关闭第二个客户端时。假设它可能在一个TCP连接关闭时停止跟踪,即使第二个TCP连接仍在运行)

这是代码的重要部分,它非常基础,来自另一个项目:

        // A few variable used throughout the program

    private static byte[] EncryptionKey = { XYZ }
    private static string filter = { XYZ }
    private static int readTimeoutMilliseconds = 1000;
    private static int defaultDevice = -1;
    private static System.Collections.Generic.List<byte> _incomingBuffer = new System.Collections.Generic.List<byte>();

    ////////////////////////////////////////////////
    static void Main(string[] args)
    {

    var devices = CaptureDeviceList.Instance;
    var device = devices[Initialization(args)];
    //Register our handler function to the 'packet arrival' event
    try
    {
    device.OnPacketArrival += new PacketArrivalEventHandler(PacketCapturer);
    }
    catch (Exception ex)
    {
    Console.WriteLine("Error registering handler! : "+ ex);
    }

    Console.WriteLine
    ("\n-- The following filter will be applied: \"{0}\"", filter);
    Console.WriteLine
    ("-- Listening on {0} {1}. \n\n Hit 'Enter' to stop...\n\n", device.Name, device.Description);


     -> This is were I would like to start again every time.. (Closing the device beforehand, so it fully resets everything.. thinking of try{device.close()}, catch ... )

    // Open the device for capturing
    device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);

    //filter to capture only packets from the Application that have data
    device.Filter = filter;

    // Start capture:
    device.StartCapture();


    // Wait for 'Enter' from the user.
    Console.ReadLine();
    device.Close();
    }

通常,我会使用一个计时器来解决这个问题,但是我不确定如何处理从main方法中仅重新启动选定的部分,因为事件处理程序以及先前选择的捕获设备都在其中注册了。

通过重新启动捕获,我希望在下降时重新启动捕获。

我应该如何处理?

很抱歉,如果这是一个棘手的问题,但是距离成为一名优秀的程序员并不遥远,我到目前为止仅从我自己的小项目中学到了。

1 个答案:

答案 0 :(得分:0)

对SharpPCap不太了解,它从代码中显示您正在重用设备实例,这很可能是第二个客户端导致它失败的原因。

在GitHub上寻找该项目,我想您可以在每次打开客户端时创建一个新实例。

更改: var device = devices[Initialization(args)]

收件人: var device = devices.New()[Initialization(args)]

Example from GitHub