Python sniffer using pypcap and dpkt on OS X

Kuaaaly picture Kuaaaly · Nov 27, 2014 · Viewed 8.4k times · Source

I'm actually trying to sniff packets with python (using pypcap and dpkt).

I tried the following :

import dpkt, pcap
pc = pcap.pcap()     # construct pcap object
pc.setfilter('src host X.X.X.X or dst host X.X.X.X')
for timestamp, packet in pc:
    print dpkt.ethernet.Ethernet(packet)

But nothing happens when I launch the script... Did I miss something ?

Using Python 2.7 On OS X Yosemite (10.10)

Answer

Briford Wylie picture Briford Wylie · Jan 2, 2016

The question is old but for new people who might hit this. The github 'chains' project uses both pypcap and dpkt for exactly this kind of thing (Disclaimer: I'm involved with all three projects :) https://github.com/SuperCowPowers/chains

  • chains/sources/packet_streamer.py (code showing use of pypcap for 'sniffing')
  • chains/links/packet_meta.py (code showing use of dpkt for packet parsing)

For those that just want to use pypcap/dpkt here's a working code snippet:

import pcap
import dpkt

sniffer = pcap.pcap(name=None, promisc=True, immediate=True)
for timestamp, raw_buf in sniffer:
    output = {}

    # Unpack the Ethernet frame (mac src/dst, ethertype)
    eth = dpkt.ethernet.Ethernet(raw_buf)
    output['eth'] = {'src': eth.src, 'dst': eth.dst, 'type':eth.type}

    # It this an IP packet?
    if not isinstance(eth.data, dpkt.ip.IP):
        print 'Non IP Packet type not supported %s\n' % eth.data.__class__.__name__
        continue 

    # Grab ip packet
    packet = eth.data

    # Pull out fragment information
    df = bool(packet.off & dpkt.ip.IP_DF)
    mf = bool(packet.off & dpkt.ip.IP_MF)
    offset = packet.off & dpkt.ip.IP_OFFMASK

    # Pulling out src, dst, length, fragment info, TTL, checksum and Protocol
    output['ip'] = {'src':packet.src, 'dst':packet.dst, 'p': packet.p,
                    'len':packet.len, 'ttl':packet.ttl,
                    'df':df, 'mf': mf, 'offset': offset,
                    'checksum': packet.sum}
    print output