Python dpkt with pcap - how can I print the packet data?

8.9k views Asked by At

I want to print out the packet data from a pcap file. The code below stores the packet data in an array but I can't figure out how to print each element of the array and then split up the data from there. A for loop on the array just returns an error.

import dpkt
import socket

f = open('test.pcap', 'r')
pcap = dpkt.pcap.Reader(f)

info = []

for ts, buf in pcap:

    eth = dpkt.ethernet.Ethernet(buf)

    if not hasattr(eth, 'ip'):
        continue
    info.append(eth.ip)

f.close()

print info
1

There are 1 answers

2
Kiran Bandla On

It is not clear what exactly you want to print. It depends on what you are looking for. If you want to print the tcp data, then here is how you do it:

import dpkt
f = open('test.pcap')
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    ip = eth.data
    tcp = ip.data

If you want to print data in a higher layer, you can extend the above example to do so. HTTP, for example, is as follows:

import dpkt

f = open('test.pcap')
pcap = dpkt.pcap.Reader(f)

for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    ip = eth.data
    tcp = ip.data
    if tcp.dport == 80:
        http = dpkt.http.Request(tcp.data)
        print http.data

For more details, see the example here, or the examples in the dpkt project.