Install & Compatibility
Where this runs
tested against v1.9.8 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.108s · 19.3MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 1.7s · import 0.094s · 20MB
17MB installed
● package 17MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
pcap
✓ from dpkt import pcap
✗ import dpkt.pcap as pcap # technically not wrong, but less common in some examples
Imports the pcap module for reading/writing .pcap files.
ethernet
✓ from dpkt import ethernet
Imports the Ethernet protocol definition.
ip
✓ from dpkt import ip
Imports the IP protocol definition.
tcp
✓ from dpkt import tcp
Imports the TCP protocol definition.
udp
✓ from dpkt import udp
Imports the UDP protocol definition.
utils
✓ from dpkt import utils
Imports utility functions, e.g., for converting MAC/IP addresses to string.
This quickstart demonstrates how to create a simple Ethernet/IP/ICMP packet, write it to a .pcap file using `dpkt.pcap.Writer`, and then read and parse that file using `dpkt.pcap.Reader`.
import dpkt
import datetime
import os
# Helper functions for printing (usually from dpkt.utils)
def mac_to_str(buf):
return ':'.join('%02x' % b for b in buf)
def ip_to_str(buf):
return '.'.join('%d' % b for b in buf)
# 1. Create a dummy pcap file for demonstration
output_pcap_file = 'test.pcap'
with open(output_pcap_file, 'wb') as f:
writer = dpkt.pcap.Writer(f, linktype=dpkt.pcap.DLT_EN10MB)
# Create a simple Ethernet frame with an IP packet and ICMP payload
eth = dpkt.ethernet.Ethernet()
eth.src = b'\x00\x11\x22\x33\x44\x55'
eth.dst = b'\xAA\xBB\xCC\xDD\xEE\xFF'
eth.type = dpkt.ethernet.ETH_TYPE_IP
ip = dpkt.ip.IP()
ip.src = b'\x7f\x00\x00\x01' # 127.0.0.1
ip.dst = b'\x7f\x00\x00\x02' # 127.0.0.2
ip.p = dpkt.ip.IP_PROTO_ICMP # Example protocol
ip.data = dpkt.icmp.ICMP(type=dpkt.icmp.ICMP_ECHO, data=dpkt.icmp.ICMP.Echo(id=1, seq=1, data=b'Hello DPKT!'))
# dpkt handles length calculation usually, but sometimes explicit setting helps
ip.len = len(ip.data) + ip.__hdr_len__
eth.data = ip
# Write the packet to the pcap file with current timestamp
writer.writepkt(eth.pack(), ts=datetime.datetime.now().timestamp())
print(f"Created '{output_pcap_file}' with a dummy packet.")
# 2. Now, read and parse the pcap file
try:
with open(output_pcap_file, 'rb') as f:
# Use dpkt.pcap.UniversalReader(f) for auto-detection of PCAP/PCAPNG
pcap_reader = dpkt.pcap.Reader(f)
print(f"\nParsing packets from '{output_pcap_file}':")
for timestamp, buf in pcap_reader:
print(f'Timestamp: {str(datetime.datetime.fromtimestamp(timestamp))}')
eth = dpkt.ethernet.Ethernet(buf)
print(f' Ethernet Frame: {mac_to_str(eth.src)} -> {mac_to_str(eth.dst)}')
if eth.type == dpkt.ethernet.ETH_TYPE_IP:
ip_packet = eth.data
print(f' IP Packet: {ip_to_str(ip_packet.src)} -> {ip_to_str(ip_packet.dst)}, Proto: {ip_packet.p}')
if ip_packet.p == dpkt.ip.IP_PROTO_ICMP:
icmp_packet = ip_packet.data
if isinstance(icmp_packet, dpkt.icmp.ICMP) and isinstance(icmp_packet.data, dpkt.icmp.ICMP.Echo):
print(f' ICMP Echo Request: ID={icmp_packet.data.id}, Seq={icmp_packet.data.seq}, Data={repr(icmp_packet.data.data)}')
else:
print(f' Non-IP Packet (Type: {hex(eth.type)})')
finally:
# Clean up the dummy file
if os.path.exists(output_pcap_file):
os.remove(output_pcap_file)
print(f"\nCleaned up '{output_pcap_file}'.")
Debug
Known issues
breakingDPKT made a significant transition from Python 2 to Python 3. Versions prior to 1.9.0 were primarily Python 2 focused (with 1.8.8 being the last Python 2 'legacy stable' release). Later versions, starting from 1.9.0, fully support Python 3 and dropped Python 2.6 support in 1.9.3.fixEnsure your environment uses Python 3.x and install dpkt >= 1.9.3. If you need Python 2, use `pip install dpkt==1.8.8` (but this is highly discouraged).
affects: <1.9.0 (Python 2 only) or 1.9.0-1.9.2 (transitional)
gotchaWhen constructing `dpkt.ip.IP` packets, earlier versions had a bug where serializing the packet would change its length attribute. This could lead to incorrect packet sizes or truncated data during transmission or re-parsing.fixUpgrade to dpkt version 1.9.8 or newer. If on an older version and explicitly setting `ip.len`, ensure to re-evaluate it after any modification or rely on dpkt's internal length calculation where possible.
affects: <1.9.8
gotchaPrior to version 1.9.8, there were known endianness issues in handling PCAPNG files, Loopback captures, and IEEE 802.11 Beacon frames, which could lead to incorrect parsing or data interpretation for these specific formats.fixUpgrade to dpkt version 1.9.8 or newer to ensure correct endianness handling for PCAPNG, Loopback, and 802.11 Beacon frames.
affects: <1.9.8
deprecatedA performance regression was introduced in `dpkt` version 1.9.7 which significantly slowed down packet processing for certain workloads.fixUsers running version 1.9.7 should immediately upgrade to 1.9.7.2 or later to fix the performance issue.
affects: 1.9.7
gotchaOlder versions of `dpkt.pcap.Reader` might not correctly handle PCAPNG files (newer pcap format). Version 1.9.7 introduced `dpkt.pcap.UniversalReader` to automatically detect and parse both PCAP and PCAPNG formats.fixFor robust handling of both PCAP and PCAPNG files, upgrade to dpkt version 1.9.7 or newer and use `dpkt.pcap.UniversalReader` instead of `dpkt.pcap.Reader`.
affects: <1.9.7
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'dpkt'
The 'dpkt' library is not installed in the Python environment being used, or the environment is not correctly configured to find the installed library.
fixInstall the dpkt library using pip: `pip install dpkt` or `pip3 install dpkt` depending on your Python setup.
AttributeError: 'str' object has no attribute 'data'
This error typically occurs when attempting to access a 'data' attribute on a `bytes` object (which `dpkt` might return if the encapsulated protocol is unknown or if a raw buffer is not an expected `dpkt` packet type), or when trying to parse a packet layer (e.g., Ethernet) that is not present in the capture (e.g., raw IP capture).
fixBefore accessing `.data`, check the type of the `eth.data` or `ip.data` object. For example, verify `eth.type` for Ethernet or `ip.p` for IP packets, and cast the data to the appropriate dpkt protocol class (e.g., `dpkt.ip.IP(buf)` for raw IP captures, `dpkt.tcp.TCP(ip.data)` for TCP).
ImportError: No module named 'ah'
This issue usually arises with older versions of dpkt or specific Python distributions where internal dependencies like 'ah' (for Authentication Header) are not properly resolved or are missing during the installation process.
fixUpgrade to the latest stable version of dpkt: `pip install --upgrade dpkt`. If the problem persists, ensure your Python environment is clean or try installing from the dpkt source repository.
ValueError: read of closed file
This error happens when the file object used to create a `dpkt.pcap.Reader` (or `dpkt.pcapng.Reader`) is closed prematurely or was not opened in binary mode, leading to an attempt to read from an invalid file descriptor during packet iteration.
fixEnsure the pcap file is opened in binary read mode (`'rb'`) and that the file handle remains open throughout the packet iteration, typically by using a `with open(...) as f:` statement.
ModuleNotFoundError: No module named 'dpkt.ethernet'
Protocol classes like Ethernet, IP, and TCP are direct members of the `dpkt` module, not nested within submodules like `dpkt.ethernet` or `dpkt.ip`.
fixImport the `dpkt` module and access the protocol classes directly, e.g., `import dpkt; eth = dpkt.ethernet.Ethernet()` or `from dpkt import ethernet, ip`.
Upgrade
Version history
1.9.8latest on PyPI · released Aug 18, 2022
Audit
Dependencies
No dependency data recorded yet.