Python pcap-ng Library

2.1.1 · active · verified Thu Apr 16

Python-pcapng is a pure-Python library designed to read and write the pcap-ng file format, which is an evolution of the traditional pcap format used by packet sniffers like Wireshark and tcpdump. It is currently at version 2.1.1 and has an active development cycle, with the last release in August 2022. The library focuses on parsing and generating pcap-ng files, providing a programmatic way to interact with these capture files where other tools might fall short.

Common errors

Warnings

Install

Imports

Quickstart

The primary use case for `python-pcapng` is to read and parse existing pcap-ng files. This quickstart demonstrates how to open a file-like object and iterate through its blocks using `FileScanner`. Each `block` object will be an instance of a specific pcap-ng block type, allowing access to its parsed data. To handle actual network traffic, replace `io.BytesIO` with `open('your_capture.pcapng', 'rb')`.

import io
from pcapng import FileScanner

# For demonstration, simulate a pcap-ng file in memory
dummy_pcapng_data = b'\n\r\r\n\x1a\x2b\x3c\x4d\x00\x00\x00\x00\x1c\x00\x00\x00\x01\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff\x1c\x00\x00\x00'
# This is a minimal, invalid SHB; a real file would be much larger and structured.
# For a proper example, generate a file using the library's writing capabilities.

try:
    with io.BytesIO(dummy_pcapng_data) as fp:
        scanner = FileScanner(fp)
        for block in scanner:
            print(f"Found block: {type(block).__name__}, Length: {block.block_len}")
            # You can access block attributes here, e.g., block.options, block.timestamp
except Exception as e:
    print(f"Error reading dummy pcap-ng: {e}")
    print("Note: The dummy_pcapng_data is highly simplified and likely incomplete for full parsing.")
    print("For a functional example, use a real pcap-ng file or generate one using FileWriter.")

view raw JSON →