pypcap icon indicating copy to clipboard operation
pypcap copied to clipboard

Unable to interrupt pypcap with zero packets received

Open vaygr opened this issue 7 years ago • 3 comments

I'm wondering if there's a workaround to interrupt pypcap process with KeyboardInterrupt if it received zero packets (e.g. with some filter set).

Currently the only option seems to be kill. But as soon as it processes the first packet, Ctrl+C starts to work fine generating the above-mentioned exception.

Or maybe I'm missing something?

vaygr avatar Nov 20 '17 18:11 vaygr

@vaygr can you provide a code snippet to reproduce the issue?

hellais avatar Nov 21 '17 09:11 hellais

Sure, I believe this is it:

#!/usr/bin/env python

import pcap

sniffer = pcap.pcap(name=None, promisc=True, immediate=True, timeout_ms=50)

pcap_filter = 'inbound and dst port 65534'

sniffer.setfilter(pcap_filter)

for _, pkt in sniffer:
    print(":)")

vaygr avatar Nov 21 '17 11:11 vaygr

I'm not really sure, but this might be related.

However I think I've got a temporary workaround using daemonized threads and signals:

#!/usr/bin/env python

import pcap
import signal
import time

from threading import Thread


class Sniffer(Thread):

    def __init__(self, sniffer):
	super(Sniffer, self).__init__()

	self.sniffer = sniffer

    def run(self):
	try:
	    for _, pkt in self.sniffer:
		print(":)")
	except KeyboardInterrupt:
	    print(":(")


if __name__ == '__main__':
    sniffer = pcap.pcap(name=None, promisc=True, immediate=True, timeout_ms=50)

    pcap_filter = 'inbound and dst port 65534'

    sniffer.setfilter(pcap_filter)

    t = Sniffer(sniffer)

    t.daemon = True

    t.start()

    signal.pause()
    # just to see the sad face if we got any packet
    time.sleep(1)

    print("aborted")

vaygr avatar Nov 21 '17 11:11 vaygr