Question

I am using pcap.net to capture packets. The method that captures packets is running in a new thread. When I want to stop/resume the capture I use the ManualResetEvent to stop/resume the thread.

it works fine, the problem is when I break the capture and start it again (stop and resume the thread) - the communicator received packets that came during the time the thread was stopped. I think its because of the buffer of the communicator.

is want the communicator to not get packets while the thread is stopped, and will get packets again when the thread is resumed. any help?

My Code:

    #region Members
    private PacketCommunicator _Communicator;
    private IList<LivePacketDevice> _allDevices;
    private PacketDevice selectedDevice;
    private Thread captureThread;
    private ManualResetEvent _pauseEvent = new ManualResetEvent(true);

    #endregion

    #region Methods

    public PacketGateway()
    {
        try
        {
            _allDevices = LivePacketDevice.AllLocalMachine;
            selectedDevice = _allDevices[0];
            captureThread = new Thread(StartListening);
        }
        catch (Exception e)
        {
            throw e;

        }
    }

    // Starts/Resumes the Thread
    public void Start()
    {
     /// Starts the Thread the first time
        if (captureThread.ThreadState == ThreadState.Unstarted)
        {
            _Communicator = selectedDevice.Open();
            captureThread.Start();
        }
     /// Resumes the Thread
        if (captureThread.ThreadState == ThreadState.WaitSleepJoin)
        {
            _pauseEvent.Set();
        }
    }


    public void Stop()
    {
        /// stop the thread
        _pauseEvent.Reset();
    }


// Starts to recieve packets
    public void StartListening()
    {
        try
        {
            _Communicator.ReceivePackets(0, HandlePacket);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


 // Handles Packet
    private void HandlePacket(Packet packet)
    {
        // some work..
    }

    #endregion

Thanks a lot!

Was it helpful?

Solution

Stopping/Starting the thread is just the wrong way to do this. Have the thread run all the time, tell it when you want to stop/start capturing, and have it throw away/process the packets depending on that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top