3

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
rcy
  • 41
  • 1
  • 2

1 Answers1

2

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.

Kiran Bandla
  • 686
  • 4
  • 10
  • Hi, thanks. For some reason when I try the http example I get an error: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/dpkt/http.py", line 131, in unpack raise dpkt.UnpackError('invalid http method: %r' % l[0]) dpkt.dpkt.UnpackError: invalid http method:'\x03\x01' What I was looking to print was the raw load / payload section of the packet. I have found that I am able to do this easily using the scapy module, so perhaps that is a better solution. – rcy Jun 22 '15 at 07:24
  • Could you share the pcap? i'd like to test it – Kiran Bandla Jun 22 '15 at 19:53