Skip to content

Stop sniff() asynchronously #989

@HenningCash

Description

@HenningCash

Hi there,
we are using scapy to built something similar to tcpdump.
The capturing process runs in its own thread:

def run(self):
    try:
        sniff(iface=self.interface, filter=self.filter, prn=self._loop_callback, store=0)
    except BaseException as e:
        log.exception(e)
    finally:
        self.output.close()

def _loop_callback(self, pkg: Packet):
    if self._stop_flag is True:
        raise KeyboardInterrupt
    else:
        self.output.write(pkg)

Basically we have a flag that is set externally from the main thread if the capturing process should stop. This works as long as a package is received after the stop flag is set. But if there is no package the thread (recv()) hangs until the next package is received and the callback is fired.

We could built something like this by passing the timeout to sniff():

    while not self._stop_flag:
        sniff(iface=self.interface, filter=self.filter, prn=self._loop_callback, store=0, timeout=1)

But I think with this approach there might be packages that get lost between the sniffing calls, am I right?

Are there any other approaches to stop sniff() async without losing packages?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions