1
votes

I am trying to parse a Pcap file in python. When i run this code

for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    print eth

I get junk values instead of getting the following output:

Ethernet(src='\x00\x1a\xa0kUf', dst='\x00\x13I\xae\x84,', data=IP(src='\xc0\xa8\n\n', off=16384, dst='C\x17\x030', sum=25129, len=52, p=6, id=51105, data=TCP(seq=9632694, off_x2=128, ack=3382015884, win=54, sum=65372, flags=17, dport=80, sport=56145)))

can anyone please tell me how to get this above output?

3

3 Answers

3
votes

Be sure the file is opened to read as binary.

https://stackoverflow.com/a/15746971

f = open(pcapfile, 'rb')
pcap = dpkt.pcap.Reader(f)

for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    print(eth)
0
votes

If the link-layer header type of the file isn't Ethernet, you will not get useful information if you try to parse the packets as Ethernet packets. The dpkt documentation isn't very good, but there's some way to get the link-layer header type; before any program reading a pcap file makes any attempt to get anything from the raw packet data, it must determine the link-layer header type in the file, and base the way it extracts information from the raw packet data on the link-layer header type (or quit if the file doesn't have a link-layer header type that it can parse).

(And feel free to tell Mr. Oberheide that his code is broken because it's not checking the link-layer header type!)

0
votes

What you have tried to do only works in a python REPL shell. When you want it to work from a python script, you need to call the repr method like so:

for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    print repr(eth)  # this is key

Ethernet(src='\x00\x1a\xa0kUf', dst='\x00\x13I\xae\x84,', data=IP(src='\xc0\xa8\n\n', off=16384, dst='C\x17\x030', sum=25129, len=52, p=6, id=51105, data=TCP(seq=9632694, off_x2=128, ack=3382015884, win=54, sum=65372, flags=17, dport=80, sport=56145)))

I am assuming that you have a pcap which has proper Ethernet packets, and you have checked like link-layer.