pythondpkt

How to fix ValueError: read of closed file while parsing a pcap using dpkt


I'm new to networking, I'm trying to parse a pcap using dpkt, but I'm getting

ValueError: read of closed file.

Here's the code:

import dpkt
f = open('test.pcapng', 'rb')
pcap = dpkt.pcap.Reader(f)
for timestamp, buf in pcap:
print (timestamp)

and this is the result:

1542964953.074129 Traceback (most recent call last): File "C:\Users\User\Documents\testdpkt1.py", line 19, in for ts, buf in pcap: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\dpkt\pcap.py", line 312, in iter buf = self.f.read(PktHdr.__hdr_len) ValueError: read of closed file


Solution

  • Have you tried?

    with open('test.pcapng', 'rb') as f:
        pcap = dpkt.pcap.Reader(f)
        for timestamp, buf in pcap:
            print (timestamp)
    

    This should prevent the file from being closed