pypcap

1.3.0 · active · verified Fri Apr 17

pypcap is a Python interface to the `libpcap` C library, enabling programmatic packet capture and analysis. It provides access to network devices and allows reading packets from live captures or pcap dump files. The current version is 1.3.0. Releases are infrequent but address Python compatibility and underlying `libpcap` features.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart captures packets on a default or specified network interface. It includes error handling for common issues like permissions and device availability. Run with `sudo` on Linux/macOS for best results.

import pcap
import os
import sys

try:
    # Try to find a default network device
    dev = pcap.lookupdev()
    if dev is None:
        print("No default network device found. Attempting to list all devices...")
        all_devs = pcap.findalldevs()
        if not all_devs:
            print("No network devices available on this system.")
            sys.exit(1)
        dev = all_devs[0] # Use the first available device as a fallback
        print(f"Using first available device: {dev}")

    # Allow overriding the device from an environment variable for easier testing
    capture_device = os.environ.get('PCAP_DEV', dev)

    print(f"Attempting to capture on device: {capture_device}")

    pc = pcap.pcap(capture_device)
    # Optional: Set a BPF filter (e.g., 'tcp port 80' or 'udp')
    # pc.setfilter('tcp')

    print("Starting packet capture (press Ctrl+C to stop)...")
    for ts, pkt in pc:
        # ts is the timestamp (float), pkt is the raw packet bytes
        print(f"[{ts}] Captured packet of length: {len(pkt)} bytes")
        # For detailed parsing, consider libraries like scapy or dpkt

except pcap.PcapError as e:
    print(f"Error initializing pcap: {e}")
    print("\nCommon issues:\n1. Lack of permissions: Try running with `sudo` (e.g., `sudo python your_script.py`).\n2. Device not found: Check if '{capture_device}' is the correct interface name (use `pcap.findalldevs()` to list).\
3. `libpcap` not installed: Ensure `libpcap-dev` (Linux) or `libpcap` (macOS) is installed.")
    sys.exit(1)
except KeyboardInterrupt:
    print("\nCapture stopped by user.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
    sys.exit(1)

view raw JSON →