Skip to main content

PyDivert

github-actions codecov latest_release docs python_versions windows license snyk

PyDivert is a high-performance, cross-platform Python binding for capturing, modifying, and dropping network packets. It supports Windows via WinDivert and Linux via eBPFDivert, an eBPF implementation of the WinDivert API. Both backends use the same filter language, layers, flags and packet metadata.

Features

  • Cross-Platform: One API for Windows (WinDivert) and Linux (eBPF), with the same semantics.
  • Seamless Multi-Handle Support: Run multiple PyDivert applications simultaneously with kernel-level priority chaining on both platforms.
  • Unified Filter Language: The same WinDivert filter strings on both platforms. On Linux they are compiled by WinDivert's own filter compiler, so they match exactly the same packets.
  • Capture network packets matching a specific filter.
  • Modify packet headers and payloads on the fly.
  • Drop unwanted packets.
  • Inject new or modified packets into the network stack.
  • Modern Python Support: Full integration with asyncio and Structural Pattern Matching (PEP 634).
  • All WinDivert 2.2 layers: NETWORK, NETWORK_FORWARD, FLOW, SOCKET and REFLECT, on both platforms.
  • Bundled Binaries: Nothing else to install. Windows wheels include the WinDivert DLL and driver; Linux wheels (x86_64, aarch64) include a self-contained libebpfdivert.so.

Requirements

  • Python 3.10+ (64-bit)
  • Windows 11 (64-bit) or Linux (experimental; x86_64/aarch64, kernel 5.10+ with BTF, glibc 2.28+; cgroup v2 for the FLOW/SOCKET layers)
  • Administrator/Root Privileges (required to interact with network drivers)

Installation

Install PyDivert using pip:

pip install pydivert

Or using uv:

uv add pydivert

The same command works on Windows and Linux; the platform wheel carries the native backend.

Quick Start

The main entry points are pydivert.Divert for cross-platform capturing and pydivert.Packet for manipulation.

Basic Capture and Re-injection (Cross-Platform)

import pydivert

# Capture only TCP packets to port 80 (HTTP requests)
with pydivert.Divert("tcp.DstPort == 80") as diverter:
    for packet in diverter:
        print(f"Captured: {packet}")
        diverter.send(packet)  # Re-inject the packet back into the stack

When you call .recv() (or iterate over the capture object), the packet is taken out of the network stack. It will not reach its destination unless you explicitly call .send(packet).

First-Class asyncio Support

PyDivert 4.0 supports asyncio natively using modern async with and async for syntax.

import asyncio
import pydivert

async def main():
    # Asynchronously capture packets
    async with pydivert.Divert("tcp.DstPort == 80") as diverter:
        async for packet in diverter:
            print(f"Async captured: {packet}")
            await diverter.send_async(packet)

if __name__ == "__main__":
    asyncio.run(main())

Common Use Cases

1. Structural Pattern Matching (PEP 634)

Filter and analyze packets using clean match/case syntax.

import pydivert
from pydivert.packet import Packet
from pydivert.packet.tcp import TCPHeader

with pydivert.Divert("tcp") as diverter:
    for packet in diverter:
        match packet:
            case Packet(tcp=TCPHeader(dst_port=80)):
                print("HTTP Traffic")
            case Packet(tcp=TCPHeader(dst_port=443)):
                print("HTTPS Traffic")
        diverter.send(packet)

2. Simple Firewall (Dropping Packets)

By simply not calling .send(packet), the packet is effectively dropped.

import pydivert

# Block all traffic from a specific IP address
with pydivert.Divert("ip.SrcAddr == 1.2.3.4") as diverter:
    for packet in diverter:
        print(f"Blocking packet from {packet.src_addr}")
        # Packet is dropped here

3. Payload Modification

You can inspect or modify the raw bytes of the packet payload.

import pydivert

# Filter for TCP packets with payload
with pydivert.Divert("tcp.PayloadLength > 0") as diverter:
    for packet in diverter:
        if b"secret-token" in packet.payload:
            # Redact the token
            packet.payload = packet.payload.replace(b"secret-token", b"REDACTED")
        diverter.send(packet)

Packet Integrity and Checksums

PyDivert can verify and recalculate network checksums automatically.

  • packet.is_checksum_valid: Returns True if all checksums (IP, TCP, UDP, ICMP) in the packet are correct.
  • packet.recalculate_checksums(): Recalculates all checksums based on the current header and payload values.
if not packet.is_checksum_valid:
    print("Corrupted packet detected!")
    packet.recalculate_checksums()

Common Packet Properties

The pydivert.Packet object provides easy access to common fields:

  • IP Layer: packet.src_addr, packet.dst_addr, packet.ip.ttl, packet.ip.protocol
  • TCP/UDP Layer: packet.src_port, packet.dst_port, packet.tcp.flags
  • Payload: packet.payload (bytes)
  • Metadata:
    • timestamp: Capture time (QueryPerformanceCounter ticks on Windows, CLOCK_MONOTONIC nanoseconds on Linux).
    • is_loopback, is_impostor, is_sniffed: Boolean flags.
    • interface: Index of the capture interface.
    • direction: Direction.INBOUND or Direction.OUTBOUND.

Detailed protocol headers are available through packet.ipv4, packet.ipv6, packet.tcp, packet.udp, and packet.icmp.

Advanced Usage

WinDivert Layers

  • Layer.NETWORK (default): IP packets to and from the local host.
  • Layer.NETWORK_FORWARD: IP packets being routed through the host.
  • Layer.FLOW: Connection established/deleted events.
  • Layer.SOCKET: Socket bind/connect/listen/accept/close events.
  • Layer.REFLECT: Divert handles opened and closed on the system.

See the Linux Backend Guide for how these are implemented on Linux, and the few differences.

Flags

  • Flag.SNIFF: Monitor mode (sniffing).
  • Flag.DROP: Drop packets by default.
  • Flag.FRAGMENTS: Capture all IP fragments.
  • Flag.RECV_ONLY / Flag.SEND_ONLY: Restricted handles.

Filter Language

Divert uses the WinDivert filter language to select which packets to capture. For a detailed reference on the syntax and available fields, see the Filter Language Guide.

For the original technical reference, please visit the official WinDivert documentation.

WinDivert/eBPF Version Compatibility

Divert Backend
4.0.0+ WinDivert 2.2.2 (bundled) / eBPFDivert 0.0.5 (bundled)
3.0.0+ WinDivert 2.2.2 (bundled) - Full support for modern metadata and layers

Development

  1. Clone the repository.
  2. Install dependencies: uv sync --extra test --extra docs
  3. Run tests (requires Admin): uv run pytest

Testing with Vagrant

PyDivert includes a Vagrantfile to easily run tests in a clean environment with the necessary privileges.

Windows (WinDivert)

To run tests on a Windows 11 VM:

vagrant up windows
# This will sync the project and run tests automatically
vagrant provision windows --provision-with test-windows

Linux (eBPF)

To run tests on a Ubuntu VM with eBPF support:

vagrant up linux
# This will run the test suite as root automatically
vagrant provision linux --provision-with test-linux
vagrant destroy -f linux

To test against a local eBPFDivert build instead of the pinned release, set PYDIVERT_EBPFDIVERT_LOCAL=/path/to/libebpfdivert.so before scripts/fetch_binaries.py, or PYDIVERT_EBPFDIVERT_LIB at runtime.

API Reference

The full API documentation is available at https://ffalcinelli.github.io/pydivert/.

License

PyDivert is dual-licensed under LGPL-3.0-or-later and GPL-2.0-or-later.

Security

PyDivert is committed to security and uses Snyk for continuous vulnerability scanning. For more details on our security practices and how to report vulnerabilities, please refer to the Security Policy.

Metadata

Release files for pydivert 4.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pydivert 4.0.1
File Size Uploaded Provenance
pydivert-4.0.1.tar.gz 65.9 kB Without provenance Details

Built distributions (wheels)

Table of built distributions (wheels) for pydivert 4.0.1
File Interpreter ABI Platform
pydivert-4.0.1-py3-none-win_amd64.whl Python 3 none Windows x86-64 Details
pydivert-4.0.1-py3-none-manylinux_2_28_x86_64.whl Python 3 none Linux glibc 2.28+ x86-64 Details
pydivert-4.0.1-py3-none-manylinux_2_28_aarch64.whl Python 3 none Linux glibc 2.28+ ARM64 Details

Total release size: 2.7 MB

Release files / pydivert-4.0.1.tar.gz

Download URL pydivert-4.0.1.tar.gz
Size 65.9 kB
Tags Source
SHA-256 checksum
How to use checksums
7de2eab52bef9005bcdb9d1ea3641b9a42bc8be8093af748d33c635d997dced2
BLAKE2b-256 checksum
How to use checksums
a3224fa2c4737dee915398f0741565f75cf8c1c9e2b75865952600f61d479f8b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / pydivert-4.0.1-py3-none-win_amd64.whl

Download URL pydivert-4.0.1-py3-none-win_amd64.whl
Size 145.2 kB
Tags Python 3 Windows x86-64
SHA-256 checksum
How to use checksums
848e8da98a39b4da056758f51b53af33cdf027d8c55eff19d910922b61347db1
BLAKE2b-256 checksum
How to use checksums
575e265b9ebe688220ee3b2d591736b546c7698c03b47deff525fff9270b63f9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / pydivert-4.0.1-py3-none-manylinux_2_28_x86_64.whl

Download URL pydivert-4.0.1-py3-none-manylinux_2_28_x86_64.whl
Size 1.3 MB
Tags Linux glibc 2.28+ x86-64 Python 3
SHA-256 checksum
How to use checksums
73eb86a3d311660fe35f22c3f91eb5479ddc8416fe4c4d57f2c5ad15daeeb46f
BLAKE2b-256 checksum
How to use checksums
ffea9cf30f9fcee1e4650970d701b86ee6a368b39b9ce0fb253280518785e9c5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / pydivert-4.0.1-py3-none-manylinux_2_28_aarch64.whl

Download URL pydivert-4.0.1-py3-none-manylinux_2_28_aarch64.whl
Size 1.3 MB
Tags Linux glibc 2.28+ ARM64 Python 3
SHA-256 checksum
How to use checksums
1985fc89d2ec495ecd180ae679375b90636ffb8f6983502e8da3a701b13d457a
BLAKE2b-256 checksum
How to use checksums
ea5634c4a1ce8ea8f501230e7902fa5de6015625e834a066c8d106ba46e0e844
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for pydivert 4.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page