kbandla / dpkt

fast, simple packet creation / parsing, with definitions for the basic TCP/IP protocols
Other
1.09k stars 270 forks source link

DPKT: Error when parsing pcap packet #593

Closed smith0818 closed 3 years ago

smith0818 commented 3 years ago

Hello, when I use dpkt to parse the pcap package, sometimes an error is reported:invalid tcpdump header.

code show as below: try: if pcap_file_path.endswith('.pcapng'):
pcap = dpkt.pcapng.Reader(pcap_file_io) elif pcap_file_path.endswith('.pcap'):
pcap = dpkt.pcap.Reader(pcap_file_io) elif pcap_file_path.endswith('.cap'):
pcap = dpkt.pcap.Reader(pcap_file_io) else: return -1 except Exception as e: logging.error("Erroe!Pcap file path:" + pcap_file_path + str(e))

Do you have any thoughts on this issue?

obormot commented 3 years ago

The pcap file extension (.pcap vs .cap vs .pcapng) doesn't always indicate the underlying file format. A better approach would be something like

pcap = None
try:
    pcap = dpkt.pcapng.Reader(pcap_file_io)
except ValueError:
    try:
        pcap = dpkt.pcap.Reader(pcap_file_io)
    except ValueError:
        ...  # failed to read both formats, log error

if pcap is not None:
    ...  # do good things
obormot commented 3 years ago

Created https://github.com/kbandla/dpkt/issues/594 to make this easier in the future versions of dpkt