pythonscapysniffing

Scapy - count number of sniffed packets?


How can I count the number of packets that I have captured using the

packets = sniff(filter='udp and host fe80::xx:xx:xx:xx',count=0)

function? Is this possible?

I've actually been trying to use prn with this function:

def packetCount(packets): 
    global counter 
    counter += 1 

I have the counter variable defined at the beginning of the program. But I need it to reset to 0 each sniff() that I do. Nothing I've tried works though...


Solution

  • sniff takes couple of parameters you might use.

    >>> print sniff.__doc__
    Sniff packets
    sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args) -> list of packets
    
      count: number of packets to capture. 0 means infinity
      store: wether to store sniffed packets or discard them
        prn: function to apply to each packet. If something is returned,
             it is displayed. Ex:
             ex: prn = lambda x: x.summary()
    lfilter: python function applied to each packet to determine
             if further action may be done
             ex: lfilter = lambda x: x.haslayer(Padding)
    offline: pcap file to read packets from, instead of sniffing them
    timeout: stop sniffing after a given time (default: None)
    L2socket: use the provided L2socket
    opened_socket: provide an object ready to use .recv() on
    stop_filter: python function applied to each packet to determine
                 if we have to stop the capture after this packet
                 ex: stop_filter = lambda x: x.haslayer(TCP)
    

    You might find timeout or count useful.

    Edit: to find the number of packets sniffed, you can use the len() function:

    len(packets)
    
    for i in range(len(packets)):
        print packets[i].summary()
    
    # or better:
    for i in packets:
        print i.summary()