Skip to main content

PyDivert

github-actions codecov latest_release docs python_versions windows license snyk

PyDivert is a powerful Python binding for WinDivert, a Windows driver that allows user-mode applications to capture, modify, and drop network packets sent to or from the Windows network stack.

Features

  • 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).
  • Support for WinDivert 2.2+ advanced features (FLOW, SOCKET, and REFLECT layers).
  • Bundled Binaries: No need to manually install WinDivert; the 64-bit DLL and driver are included.

Requirements

  • Python 3.10+ (64-bit)
  • Windows 11 (64-bit)
  • Administrator Privileges (required to interact with the WinDivert driver)

[!NOTE] Windows Server is currently untested but likely works if it meets the architecture requirements.

Installation

Install PyDivert using pip:

pip install pydivert

Or using uv:

uv add pydivert

Quick Start

The main entry points are pydivert.WinDivert for capturing and pydivert.Packet for manipulation.

[!TIP] All code examples in this README are verified by automated integration tests in pydivert/tests/test_readme_examples.py.

Basic Capture and Re-injection

import pydivert

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

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

First-Class asyncio Support

PyDivert 3.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.WinDivert("tcp.DstPort == 80") as w:
        async for packet in w:
            print(f"Async captured: {packet}")
            await w.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.WinDivert("tcp") as w:
    for packet in w:
        match packet:
            case Packet(tcp=TCPHeader(dst_port=80)):
                print("HTTP Traffic")
            case Packet(tcp=TCPHeader(dst_port=443)):
                print("HTTPS Traffic")
        w.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.WinDivert("ip.SrcAddr == 1.2.3.4") as w:
    for packet in w:
        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.WinDivert("tcp.PayloadLength > 0") as w:
    for packet in w:
        if b"secret-token" in packet.payload:
            # Redact the token
            packet.payload = packet.payload.replace(b"secret-token", b"REDACTED")
        w.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).
    • 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.
  • Layer.FLOW: Connection events.
  • Layer.SOCKET: Socket-level events.
  • Layer.REFLECT: Reflected events.

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

PyDivert 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 Version Compatibility

PyDivert WinDivert
3.0.0+ 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

Since WinDivert requires Windows, use Vagrant to run tests on a Windows 11 VM:

vagrant up
vagrant powershell -c '$env:UV_PROJECT_ENVIRONMENT="C:/pydivert_venv"; cd C:/pydivert; uv run pytest'

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.

Release files for pydivert 3.1.3

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 3.1.3
File Size Uploaded
pydivert-3.1.3.tar.gz 124.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for pydivert 3.1.3
File Interpreter ABI Platform
pydivert-3.1.3-py3-none-any.whl Python 3 none any Details

Total release size: 273.5 kB

Release files / pydivert-3.1.3.tar.gz

Download URL pydivert-3.1.3.tar.gz
Size 124.4 kB
Tags Source
SHA-256 checksum
How to use checksums
e5cba087f3f17eb66cf50965cf9670c55691c580f81dcad20549a0ef49af8e06
BLAKE2b-256 checksum
How to use checksums
5f19dada7b2efd40eaaa7d5fc4d14f85c9e8aaf4eeacb23fc9294768fe6e44e2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.11.14 {"installer":{"name":"uv","version":"0.11.14","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-3.1.3-py3-none-any.whl

Download URL pydivert-3.1.3-py3-none-any.whl
Size 149.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
74ae83a5d1b4a31db8f84a55c1cf875eb4e7a0d2bc2e4730ef171819bc5e9008
BLAKE2b-256 checksum
How to use checksums
da66323e91ceb1aeef828d7b39860637c8d2723ac4020ccb6cfbc7fdfa474249
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.11.14 {"installer":{"name":"uv","version":"0.11.14","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 history Release notifications | RSS feed

This release

3.1.3 This release

2 release files

3.1.2

2 release files

3.1.1

2 release files

3.1.0

2 release files

3.0.0

2 release files

2.1.0

2 release files

2.0.9

2 release files

2.0.7

2 release files

2.0.6

2 release files

2.0.5

2 release files

2.0.4

2 release files

2.0.3

2 release files

2.0.1

2 release files

2.0.0

2 release files

1.0.2

3 release files

1.0.1

1 release file

0.1

0.0.7

1 release file

0.0.6

1 release file

0.0.5

1 release file

0.0.4

1 release file

0.0.3

1 release file

0.0.2

1 release file

0.0.1

1 release file

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