Scapy packet sniffer triggering an action up on each sniffed packet

RatDon picture RatDon · Feb 3, 2015 · Viewed 43.2k times · Source

I'm using scapy with python to sniff live traffic.

capture=sniff(iface="<My Interface>", filter="tcp")

But this sniffs each packet and adds it to the list capture which can be processed later.

I want to process a packet and display few fields of the packet, as soon as it's sniffed. i.e. upon sniffing a packet, it'll trigger a function where I can analyse that packet. And this would continue for few packets.

I've the function ready which I'm using with the captured packet list. But I'm unable to use it for each live packet.

How to achieve that? Is it possible with scapy or do I need to install any other package?

Answer

RatDon picture RatDon · Mar 3, 2015

The parameters to the sniff function should be like the below code.:

from scapy.all import *

def pkt_callback(pkt):
    pkt.show() # debug statement

sniff(iface="<My Interface>", prn=pkt_callback, filter="tcp", store=0)

store=0 says not to store any packet received and prn says send the pkt to pkt_callback.

Source.

As mentioned by Yoel, if only one action is required, lambda can be used with prn instead of a new function like in this case:

sniff(iface="<My Interface>", prn = lambda x: x.show(), filter="tcp", store=0)