pynetwork / pypcap

pypcap - python libpcap module, forked from code.google.com/p/pypcap
Other
299 stars 74 forks source link

Unable to interrupt pypcap with zero packets received #60

Open vaygr opened 6 years ago

vaygr commented 6 years ago

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?

hellais commented 6 years ago

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

vaygr commented 6 years ago

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 commented 6 years ago

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")