Scapy AsyncSniffer fails if stop() is called right after start()

1.3k views Asked by At

Look at the following example

a = AsyncSniffer()
a.start()
a.stop()

a.stop() will throw an exception. Is there a way to fix this without adding a time.sleep() between the start() and stop()?

  • this ofcourse is a contrived example but the code in our project has the same problem if I create a test stub in between the start() and the stop()

Update: tracebak from pycharm run:

FAILED                         [100%]
test_async_sniffer.py:3 (test_async_sniffer)
self = <scapy.sendrecv.AsyncSniffer object at 0x7f1d57a7f1f0>, join = True

    def stop(self, join=True):
        """Stops AsyncSniffer if not in async mode"""
        if self.running:
            try:
>               self.stop_cb()
E               AttributeError: 'AsyncSniffer' object has no attribute 'stop_cb'

venv/lib/python3.8/site-packages/scapy/sendrecv.py:1017: AttributeError

During handling of the above exception, another exception occurred:

    def test_async_sniffer():
        a = AsyncSniffer()
        a.start()
>       a.stop()

test_async_sniffer.py:7: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <scapy.sendrecv.AsyncSniffer object at 0x7f1d57a7f1f0>, join = True

    def stop(self, join=True):
        """Stops AsyncSniffer if not in async mode"""
        if self.running:
            try:
                self.stop_cb()
            except AttributeError:
>               raise Scapy_Exception(
                    "Unsupported (offline or unsupported socket)"
                )
E               scapy.error.Scapy_Exception: Unsupported (offline or unsupported socket)

venv/lib/python3.8/site-packages/scapy/sendrecv.py:1019: Scapy_Exception
1

There are 1 answers

1
adamlapidoth On

A possible answer although not pretty:

    a = AsyncSniffer()
    a.start()
    if not hasattr(a, 'stop_cb'):
        time.sleep(0.06)
    a.stop()

seems the start() creates the attribute stop_cb, and if stop() is called right after start() the stop_cb has not been created yet, so I add an hasattr with a sleep (testing shows 0.06 secs is sufficient time but I guess it's very arbitrary)