{"library":"pypcap","title":"pypcap","description":"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.","language":"python","status":"active","last_verified":"Fri Apr 17","install":{"commands":["pip install pypcap"],"cli":null},"imports":["import pcap"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import pcap\nimport os\nimport sys\n\ntry:\n    # Try to find a default network device\n    dev = pcap.lookupdev()\n    if dev is None:\n        print(\"No default network device found. Attempting to list all devices...\")\n        all_devs = pcap.findalldevs()\n        if not all_devs:\n            print(\"No network devices available on this system.\")\n            sys.exit(1)\n        dev = all_devs[0] # Use the first available device as a fallback\n        print(f\"Using first available device: {dev}\")\n\n    # Allow overriding the device from an environment variable for easier testing\n    capture_device = os.environ.get('PCAP_DEV', dev)\n\n    print(f\"Attempting to capture on device: {capture_device}\")\n\n    pc = pcap.pcap(capture_device)\n    # Optional: Set a BPF filter (e.g., 'tcp port 80' or 'udp')\n    # pc.setfilter('tcp')\n\n    print(\"Starting packet capture (press Ctrl+C to stop)...\")\n    for ts, pkt in pc:\n        # ts is the timestamp (float), pkt is the raw packet bytes\n        print(f\"[{ts}] Captured packet of length: {len(pkt)} bytes\")\n        # For detailed parsing, consider libraries like scapy or dpkt\n\nexcept pcap.PcapError as e:\n    print(f\"Error initializing pcap: {e}\")\n    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).\\\n3. `libpcap` not installed: Ensure `libpcap-dev` (Linux) or `libpcap` (macOS) is installed.\")\n    sys.exit(1)\nexcept KeyboardInterrupt:\n    print(\"\\nCapture stopped by user.\")\nexcept Exception as e:\n    print(f\"An unexpected error occurred: {e}\")\n    sys.exit(1)","lang":"python","description":"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.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}