Pure-pcapy3

1.0.1 · active · verified Fri Apr 17

pure-pcapy3, currently at version 1.0.1, is a pure Python reimplementation of the `pcapy` library, designed to be API compatible and a drop-in replacement. It allows Python programs to capture live network traffic and read/write pcap files without requiring C extensions. While aiming for full compatibility, its release cadence is infrequent, focusing on stability.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `pure-pcapy3` for live packet capture on a specified network interface. It includes a basic packet handler and a fallback mechanism to illustrate opening a pcap file. Remember to replace `'eth0'` with an actual network interface on your system (e.g., `'wlan0'`, `'en0'`) and ensure your user has permissions to capture packets (e.g., by running with `sudo` or being in the appropriate user group).

import pcapy
import sys

def packet_handler(header, data):
    # This is a very basic handler. Real-world usage would parse 'data'.
    print(f"Captured packet! Length: {header.getlen()} bytes")

# Try to open 'eth0' or 'en0' (common interface names)
# Fallback to an example pcap file if live capture fails or is not desired.
interface = 'eth0' # Change to your network interface, e.g., 'wlan0', 'en0'
try:
    # Open live capture on a network interface
    # interface, snaplen, promiscuous_mode, timeout_ms
    pc = pcapy.open_live(interface, 1500, True, 100)
    print(f"Listening on interface: {interface}...")
    print("Press Ctrl+C to stop.")
    pc.loop(0, packet_handler) # 0 for infinite loop
except pcapy.PcapError as e:
    print(f"Error opening live capture on {interface}: {e}")
    print("Trying to open a dummy pcap file instead.")
    # Fallback to a dummy pcap file for demonstration if live capture fails
    # (e.g., no permissions, interface not found)
    try:
        # For a runnable example without requiring live interface access, you'd usually have a .pcap file.
        # This example assumes you might have 'test.pcap' or similar.
        # If not, this part will also fail.
        # Create a dummy pcap file if it doesn't exist for the example:
        import os
        dummy_pcap_path = 'dummy.pcap'
        if not os.path.exists(dummy_pcap_path):
            print(f"Warning: '{dummy_pcap_path}' not found. Cannot demonstrate file reading.")
        else:
            print(f"Opening pcap file: {dummy_pcap_path}")
            pc_file = pcapy.open_offline(dummy_pcap_path)
            pc_file.loop(0, packet_handler)
    except pcapy.PcapError as e_file:
        print(f"Error opening pcap file '{dummy_pcap_path}': {e_file}")
        print("Please ensure you have necessary permissions or a valid pcap file.")
except KeyboardInterrupt:
    print("Capture stopped by user.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →