Skip to main content

Crate netring

Crate netring 

Source
Expand description

§netring

High-performance zero-copy packet I/O for Linux.

netring provides packet capture and injection via AF_PACKET (TPACKET_V3 block-based mmap ring buffers) and AF_XDP (kernel-bypass via XDP sockets). It offers both a high-level ergonomic API and a low-level batch API for maximum throughput.

§Quick Start

// High-level: flat packet iterator
let mut cap = netring::Capture::new("eth0").unwrap();
for pkt in cap.packets().take(100) {
    println!("[{}] {} bytes", pkt.timestamp(), pkt.len());
}
// Low-level: batch processing with sequence gap detection
use netring::{AfPacketRxBuilder, PacketSource};
use std::time::Duration;

let mut rx = AfPacketRxBuilder::default()
    .interface("eth0")
    .block_size(1 << 22)
    .build()
    .unwrap();

while let Some(batch) = rx.next_batch_blocking(Duration::from_millis(100)).unwrap() {
    println!("seq={} pkts={} timed_out={}",
        batch.seq_num(), batch.len(), batch.timed_out());
    for pkt in &batch {
        process(pkt.data());
    }
    // batch dropped → block returned to kernel
}

§Features

FeatureDefaultDescription
af-xdpoffAF_XDP kernel-bypass packet I/O (pure Rust, no native deps)
tokiooffAsync capture via AsyncFd (wait_readable + next_batch)
channeloffThread + bounded channel adapter (runtime-agnostic)
parseoffPacket header parsing via etherparse

§API Levels

LevelTypesWhen to Use
HighCapture, InjectorSimple capture/inject with iterators and builders
LowAfPacketRx, AfPacketTxBatch processing, sequence tracking, custom poll logic
AF_XDPXdpSocket, XdpSocketBuilderKernel-bypass via AF_XDP (feature: af-xdp)
AsyncAsyncCapture, ChannelCaptureIntegration with tokio or any async runtime

§Default Configuration

ParameterDefaultDescription
block_size4 MiBRing buffer block size
block_count64Number of blocks (256 MiB total)
frame_size2048Minimum frame size
block_timeout_ms60Block retirement timeout
fill_rxhashtrueKernel fills RX flow hash

§Performance Tuning

Profileblock_sizeblock_counttimeout_msNotes
High throughput4 MiB128–25660+ FanoutMode::Cpu + thread pinning
Low latency256 KiB641–10+ busy_poll_us(50)
Memory-constrained1 MiB1610016 MiB total ring
Jumbo frames4 MiB6460frame_size(65536)

See docs/TUNING_GUIDE.md for detailed tuning advice.

§Fanout Modes

Distribute packets across multiple sockets for multi-threaded capture:

ModeStrategy
HashFlow hash (same flow → same socket)
CpuRoute to CPU that received the NIC interrupt
LoadBalanceRound-robin
RolloverFill one socket, overflow to next
RandomRandom distribution
QueueMappingNIC hardware queue mapping
use netring::{Capture, FanoutMode, FanoutFlags};

let cap = Capture::builder()
    .interface("eth0")
    .fanout(FanoutMode::Cpu, 42)
    .fanout_flags(FanoutFlags::ROLLOVER | FanoutFlags::DEFRAG)
    .build()
    .unwrap();

§Statistics

let stats = cap.stats().unwrap();
println!("received: {}, dropped: {}, frozen: {}",
    stats.packets, stats.drops, stats.freeze_count);

Reading stats resets the kernel counters — call periodically for rate calculation.

§System Requirements

  • Linux kernel 3.2+ (for TPACKET_V3), 5.4+ (for AF_XDP)
  • Rust 1.85+ (edition 2024)

§Capabilities

CapabilityRequired For
CAP_NET_RAWCreating AF_PACKET / AF_XDP sockets
CAP_IPC_LOCKMAP_LOCKED (or sufficient RLIMIT_MEMLOCK)
CAP_NET_ADMINPromiscuous mode
# Recommended: use justfile (sudo only once for setcap)
just setcap          # grants CAP_NET_RAW on all binaries
just test            # runs without sudo
just capture eth0    # runs without sudo

# Manual alternative
sudo setcap cap_net_raw+ep target/release/examples/capture

§Examples

just setcap                  # grant capabilities once (needs sudo)
just capture eth0            # basic packet capture
just batch eth0              # low-level batch API with sequence gap detection
just fanout eth0 4           # multi-threaded fanout capture
just inject lo               # packet injection
just stats eth0              # live statistics monitor (pkt/s, drops)
just low-latency eth0        # low-latency tuning demo
just dpi eth0                # deep packet inspection (HTTP/TLS/DNS/SSH detection)
just channel eth0            # channel adapter (runtime-agnostic)
just async eth0              # async capture with tokio
just ebpf                    # eBPF/aya integration demo (AsFd verification)
cargo run --example xdp_send --features af-xdp -- lo  # AF_XDP TX-only

§Documentation

§License

Licensed under either of Apache License, Version 2.0 or MIT License at your option.

Re-exports§

pub use capture::Capture;
pub use capture::CaptureBuilder;
pub use config::BpfFilter;
pub use config::BpfInsn;
pub use config::FanoutFlags;
pub use config::FanoutMode;
pub use config::RingProfile;
pub use config::TimestampSource;
pub use error::Error;
pub use inject::Injector;
pub use inject::InjectorBuilder;
pub use interface::InterfaceInfo;
pub use interface::interface_info;
pub use packet::OwnedPacket;
pub use packet::Packet;
pub use packet::PacketBatch;
pub use packet::PacketDirection;
pub use packet::PacketStatus;
pub use packet::Timestamp;
pub use stats::CaptureStats;
pub use traits::PacketSink;
pub use traits::PacketSource;
pub use afpacket::rx::AfPacketRx;
pub use afpacket::rx::AfPacketRxBuilder;
pub use afpacket::tx::AfPacketTx;
pub use afpacket::tx::AfPacketTxBuilder;
pub use afpacket::tx::TxSlot;
pub use afxdp::XdpSocket;
pub use afxdp::XdpSocketBuilder;
pub use bridge::Bridge;
pub use bridge::BridgeAction;
pub use bridge::BridgeBuilder;
pub use bridge::BridgeDirection;
pub use bridge::BridgeStats;
pub use async_adapters::channel::ChannelCapture;
pub use async_adapters::tokio_adapter::AsyncCapture;
pub use traits::AsyncPacketSource;

Modules§

afpacket
AF_PACKET backend implementation.
afxdp
AF_XDP backend for kernel-bypass packet I/O.
async_adapters
Async and channel adapters for packet capture.
bridge
Bidirectional packet bridge between two interfaces (IPS mode).
capture
High-level packet capture API.
config
Configuration types: fanout, BPF filters, timestamps.
error
Error types for netring.
inject
High-level packet injection.
interface
Interface capability detection.
packet
Packet types: zero-copy views, batch iteration, timestamps, and owned packets.
stats
Capture statistics.
traits
Core traits for packet capture and injection.