Parsing a PCAP File in python

10,431

Solution 1

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)

Solution 2

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!)

Share:
10,431
Normal one
Author by

Normal one

Updated on June 04, 2022

Comments

  • Normal one
    Normal one almost 2 years

    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?