{"id":3981,"library":"dpkt","title":"DPKT Packet Manipulation Library","description":"DPKT is a fast, simple Python library for creating and parsing network packets, providing definitions for many common TCP/IP protocols like Ethernet, IP, TCP, and UDP. Its current stable version is 1.9.8, with releases occurring semi-regularly, focusing on bug fixes, protocol updates, and performance improvements.","status":"active","version":"1.9.8","language":"en","source_language":"en","source_url":"https://github.com/kbandla/dpkt","tags":["networking","packet-parsing","pcap","protocol-analysis","network-security"],"install":[{"cmd":"pip install dpkt","lang":"bash","label":"Install latest version"}],"dependencies":[],"imports":[{"note":"Imports the pcap module for reading/writing .pcap files.","wrong":"import dpkt.pcap as pcap # technically not wrong, but less common in some examples","symbol":"pcap","correct":"from dpkt import pcap"},{"note":"Imports the Ethernet protocol definition.","symbol":"ethernet","correct":"from dpkt import ethernet"},{"note":"Imports the IP protocol definition.","symbol":"ip","correct":"from dpkt import ip"},{"note":"Imports the TCP protocol definition.","symbol":"tcp","correct":"from dpkt import tcp"},{"note":"Imports the UDP protocol definition.","symbol":"udp","correct":"from dpkt import udp"},{"note":"Imports utility functions, e.g., for converting MAC/IP addresses to string.","symbol":"utils","correct":"from dpkt import utils"}],"quickstart":{"code":"import dpkt\nimport datetime\nimport os\n\n# Helper functions for printing (usually from dpkt.utils)\ndef mac_to_str(buf):\n    return ':'.join('%02x' % b for b in buf)\ndef ip_to_str(buf):\n    return '.'.join('%d' % b for b in buf)\n\n# 1. Create a dummy pcap file for demonstration\noutput_pcap_file = 'test.pcap'\nwith open(output_pcap_file, 'wb') as f:\n    writer = dpkt.pcap.Writer(f, linktype=dpkt.pcap.DLT_EN10MB)\n\n    # Create a simple Ethernet frame with an IP packet and ICMP payload\n    eth = dpkt.ethernet.Ethernet()\n    eth.src = b'\\x00\\x11\\x22\\x33\\x44\\x55'\n    eth.dst = b'\\xAA\\xBB\\xCC\\xDD\\xEE\\xFF'\n    eth.type = dpkt.ethernet.ETH_TYPE_IP\n\n    ip = dpkt.ip.IP()\n    ip.src = b'\\x7f\\x00\\x00\\x01' # 127.0.0.1\n    ip.dst = b'\\x7f\\x00\\x00\\x02' # 127.0.0.2\n    ip.p = dpkt.ip.IP_PROTO_ICMP # Example protocol\n    ip.data = dpkt.icmp.ICMP(type=dpkt.icmp.ICMP_ECHO, data=dpkt.icmp.ICMP.Echo(id=1, seq=1, data=b'Hello DPKT!'))\n    \n    # dpkt handles length calculation usually, but sometimes explicit setting helps\n    ip.len = len(ip.data) + ip.__hdr_len__ \n\n    eth.data = ip\n\n    # Write the packet to the pcap file with current timestamp\n    writer.writepkt(eth.pack(), ts=datetime.datetime.now().timestamp())\n\nprint(f\"Created '{output_pcap_file}' with a dummy packet.\")\n\n# 2. Now, read and parse the pcap file\ntry:\n    with open(output_pcap_file, 'rb') as f:\n        # Use dpkt.pcap.UniversalReader(f) for auto-detection of PCAP/PCAPNG\n        pcap_reader = dpkt.pcap.Reader(f)\n\n        print(f\"\\nParsing packets from '{output_pcap_file}':\")\n        for timestamp, buf in pcap_reader:\n            print(f'Timestamp: {str(datetime.datetime.fromtimestamp(timestamp))}')\n            eth = dpkt.ethernet.Ethernet(buf)\n            print(f'  Ethernet Frame: {mac_to_str(eth.src)} -> {mac_to_str(eth.dst)}')\n\n            if eth.type == dpkt.ethernet.ETH_TYPE_IP:\n                ip_packet = eth.data\n                print(f'  IP Packet: {ip_to_str(ip_packet.src)} -> {ip_to_str(ip_packet.dst)}, Proto: {ip_packet.p}')\n                \n                if ip_packet.p == dpkt.ip.IP_PROTO_ICMP:\n                    icmp_packet = ip_packet.data\n                    if isinstance(icmp_packet, dpkt.icmp.ICMP) and isinstance(icmp_packet.data, dpkt.icmp.ICMP.Echo):\n                        print(f'    ICMP Echo Request: ID={icmp_packet.data.id}, Seq={icmp_packet.data.seq}, Data={repr(icmp_packet.data.data)}')\n\n            else:\n                print(f'  Non-IP Packet (Type: {hex(eth.type)})')\n\nfinally:\n    # Clean up the dummy file\n    if os.path.exists(output_pcap_file):\n        os.remove(output_pcap_file)\n        print(f\"\\nCleaned up '{output_pcap_file}'.\")","lang":"python","description":"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`."},"warnings":[{"fix":"Ensure 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).","message":"DPKT 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.","severity":"breaking","affected_versions":"<1.9.0 (Python 2 only) or 1.9.0-1.9.2 (transitional)"},{"fix":"Upgrade 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.","message":"When 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.","severity":"gotcha","affected_versions":"<1.9.8"},{"fix":"Upgrade to dpkt version 1.9.8 or newer to ensure correct endianness handling for PCAPNG, Loopback, and 802.11 Beacon frames.","message":"Prior 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.","severity":"gotcha","affected_versions":"<1.9.8"},{"fix":"Users running version 1.9.7 should immediately upgrade to 1.9.7.2 or later to fix the performance issue.","message":"A performance regression was introduced in `dpkt` version 1.9.7 which significantly slowed down packet processing for certain workloads.","severity":"deprecated","affected_versions":"1.9.7"},{"fix":"For 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`.","message":"Older 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.","severity":"gotcha","affected_versions":"<1.9.7"}],"env_vars":null,"last_verified":"2026-04-11T00:00:00.000Z","next_check":"2026-07-10T00:00:00.000Z"}