Search code examples
c++keyboardkeyboard-eventspcaplibpcap

Winpcap: pcap_breakloop function to pause/stop sniffing won't work


So for my final year project/dissertation at university I am coding a packet sniffer using C++ and pcap. The program at the moment can sniff packets however I am trying to code it so that when the escape key is pressed, sniffing will stop. This is the piece of code in question:

while ((result = pcap_loop(adhandle, 0, packet_handler, NULL)) == 0) {

        if (result == 0)
            continue;

        if (GetAsyncKeyState(VK_ESCAPE))
        {
            result = -2;
        }

        if (result == -2)
        {
            pcap_breakloop(adhandle);
        }
    }

When the escape key is pressed nothing happens and sniffing continues until the program is closed. Any help as to why this is not working will be much appreciated!


Solution

  • From the documentation on pcap_loop:

    pcap_loop() processes packets from a live capture or ''savefile'' until cnt packets are processed, the end of the ''savefile'' is reached when reading from a ''savefile'', pcap_breakloop() is called, or an error occurs. It does not return when live read timeouts occur. A value of -1 or 0 for cnt is equivalent to infinity, so that packets are processed until another ending condition occurs.

    Because your second argument to pcap_loop is 0, it will process packets indefinitely, and won't reach your while loop body unless an error occurs.