Datalink layer packet rx/tx, attempting to be a spiritual successor to libpnet (At least the datalink side)
README.md

ferranet #

⚠️ Beta — use with care. The core paths are exercised by unit, property, fuzz, Miri, and CI-run veth integration tests, and the AF_PACKET backends (ring and basic) have been validated on real hardware — a Raspberry Pi Zero 2 W over a direct ethernet link, under the pibench capture and flood workloads. Known gaps: the AF_XDP backend runs end-to-end over veth (generic/copy mode) but is unvalidated on a real NIC (zero-copy, multi-queue), the throughput numbers in BENCHMARKS.md are still veth-only, and the API may see further breaking changes before 1.0. Review the unsafe yourself before relying on it.

A modern, async-first, zero-copy datalink-layer (Layer 2) networking library for Rust.

ferranet lets you open a network interface and send/receive raw Ethernet frames with batching and zero-copy receive. It is a spiritual successor to pnet's datalink module, rebuilt around the lessons its original author shared in a retrospective:

  • Async first. A Tokio-based API is the primary surface, with a blocking API for maximum-throughput use.
  • Zero-copy receive. Received frames borrow directly from a kernel-mapped PACKET_MMAP ring and are valid "until the end of the block" — no copying.
  • Batching. A TPACKET_V3 RX ring (block-based) and TPACKET_V2 TX ring amortize syscalls.
  • Justified unsafe. All unsafe is concentrated in one module, each block carrying a SAFETY argument resting on the kernel's TP_STATUS_* ownership protocol.
  • The fd is yours. as_fd() exposes the underlying descriptor for interop.
  • Kernel-side filtering. Attach a compiled classic-BPF program (ChannelBuilder::filter) so the kernel drops non-matching frames before they are ever copied to user space.

Status #

v0.3, Linux only, behind a sys::RawChannel abstraction boundary so other platforms (BSD/macOS, Windows) can be added later without API churn. Two backends ship today:

  • AF_PACKET/PACKET_MMAP (default) — the zero-copy TPACKET_V3 RX ring / TPACKET_V2 TX ring.
  • AF_XDP (optional, --features xdp, experimental) — the kernel-bypass tier. XdpSocket drives the UMEM and fill/completion/RX/TX rings; steering traffic in still requires an XDP redirect program (see below). It has only been exercised over veth in generic mode and is outside the 0.3.0 release-readiness review, which covered the AF_PACKET backends only.

Packet parsing/construction is intentionally out of scope (a separate concern).

The default ring backend needs Linux ≥ 3.2; the AF_XDP backend needs ≥ 4.18. See docs/kernel-compat.md for the per-feature kernel matrix and required capabilities.

Interface enumeration includes per-interface IP addresses: ferranet::interfaces() returns Interface { name, index, mac, ips, flags, mtu }, where each IfAddr carries the address, its netmask, and a prefix_len().

Roadmap / TODO #

Before a 1.0 this needs, roughly in priority order:

Packet parsing/construction stays out of scope by design — pair ferranet with etherparse for dissection.

AF_XDP (xdp feature) #

# #[cfg(feature = "xdp")]
# fn run() -> ferranet::Result<()> {
use ferranet::{XdpConfig, XdpSocket, interfaces};

let idx = interfaces()?.into_iter().find(|i| i.name == "eth0").unwrap().index;
let mut sock = XdpSocket::open(idx, XdpConfig { queue_id: 0, ..XdpConfig::default() })?;
let block = sock.recv()?;                 // zero-copy frames from the UMEM
for frame in block.frames() { /* ... */ }
# Ok(())
# }

Unlike AF_PACKET, an AF_XDP socket only receives frames that an XDP program redirects into its XSKMAP for the bound (interface, queue) — the kernel ships no default. With the xdp-loader feature, ferranet embeds and attaches a built-in redirect program for you, so the backend is turnkey:

# #[cfg(feature = "xdp-loader")]
# fn run() -> ferranet::Result<()> {
use ferranet::{XdpConfig, XdpSocket, interfaces};

let idx = interfaces()?.into_iter().find(|i| i.name == "eth0").unwrap().index;
let mut sock = XdpSocket::open(idx, XdpConfig { queue_id: 0, ..XdpConfig::default() })?;
let _guard = sock.attach_redirect("eth0")?;  // attaches in generic (SKB) mode; drop to detach
let block = sock.recv()?;
# Ok(())
# }

attach_redirect needs CAP_BPF/CAP_NET_ADMIN in the initial namespace (a user namespace is not enough) and attaches in generic (SKB) mode, which works on any driver including veth. Without the feature, attaching the redirect program is left to the operator or a higher layer (libxdp/aya/ xdp-loader), exactly as libxdp and xsk-rs separate the socket from the program. The data-path math is unit-tested; end-to-end use needs a real NIC/queue (or veth in generic XDP mode) with a redirect program attached.

Example #

use ferranet::Channel;

#[tokio::main]
async fn main() -> ferranet::Result<()> {
    let (mut tx, mut rx) = Channel::builder("eth0").promiscuous(true).build_async()?;

    // Zero-copy, batched receive.
    let block = rx.recv_block().await?;
    for frame in block.frames() {
        println!("{} bytes, type {:?}", frame.data().len(), frame.packet_type());
    }

    // Send a raw frame (must include the Ethernet header for SOCK_RAW).
    tx.send(b"\xff\xff\xff\xff\xff\xff\x02\x00\x00\x00\x00\x01\x88\xb5hi").await?;
    Ok(())
}

A blocking equivalent is available via Channel::builder(..).build_sync().

Multi-core receive (PACKET_FANOUT) #

Open a group of receivers and let the kernel load-balance frames across them — one per core:

use ferranet::{Channel, FanoutMode};

# fn main() -> ferranet::Result<()> {
let receivers = Channel::builder("eth0")
    .fanout(FanoutMode::Hash)        // flow-consistent steering
    .build_fanout_rx(4)?;            // 4 sockets in one fanout group

for mut rx in receivers {
    std::thread::spawn(move || {
        loop {
            let block = rx.recv_block()?;
            for frame in block.frames() { /* ... */ }
        }
        # #[allow(unreachable_code)] ferranet::Result::Ok(())
    });
}
# Ok(())
# }

build_fanout_rx_async returns AsyncReceivers for the same pattern on Tokio.

Bounded receive #

recv_block blocks indefinitely, which is awkward for a capture thread that must periodically notice a shutdown flag even on a quiet interface. recv_block_timeout bounds the wait and distinguishes "nothing arrived" from "data" and from "error" through the return type itself, no string/error-kind matching required:

use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

# fn run(shutdown: &AtomicBool) -> ferranet::Result<()> {
let (_tx, mut rx) = ferranet::Channel::builder("eth0").build_sync()?;
while !shutdown.load(Ordering::Relaxed) {
    match rx.recv_block_timeout(Duration::from_millis(200))? {
        Some(block) => {
            for frame in block.frames() { /* ... */ }
        }
        None => continue, // quiet interface; go re-check the shutdown flag
    }
}
# Ok(())
# }

A timeout never consumes kernel state — nothing is read until data is actually available — so it never loses a frame or leaves a ring block half-handled; recv_block is just this call with an unbounded wait. The deadline is fixed when the call starts: interrupted waits (EINTR from a profiler's SIGPROF, say) resume with the remaining time, so signals cannot stretch a finite timeout. Socket failure — the interface going down or being deleted — surfaces as Error::Recv, not as an endless run of Ok(None), on both the sync and async receivers. Only the sync API has the timeout itself; the async API gets the equivalent for free from tokio::time::timeout.

Transmit contract #

send returns Ok once the frame has been handed to the kernel's transmit path — with a TX ring, that means the kernel has actually picked the slot up, not merely that it was queued. A frame the kernel rejects (over the device MTU, say) is reported, and the ring recovers: the next valid frame goes out immediately rather than after a full ring wrap.

send_batch fills as many ring slots as it can with one flushing syscall. If the kernel rejects a frame part-way, the error is Error::BatchSend { accepted, source }: exactly the first accepted frames were handed over, the rest were withdrawn from the ring and are yours to retry — retry only that suffix to avoid duplicates. Over-size frames are rejected locally before anything is queued.

SOCK_DGRAM channels (ChannelBuilder::dgram) are receive-only: the kernel would need a destination address to synthesise a link-layer header, which the API does not carry, so send returns an Unsupported error rather than silently doing the wrong thing.

Kernel-side filtering (cBPF) #

ChannelBuilder::protocol filters by EtherType only. For anything finer — a UDP destination port, say — attach a compiled classic-BPF program so the kernel drops non-matching frames before they are copied to user space at all, instead of copying everything and discarding most of it in user-space:

use ferranet::{BpfInsn, Channel};

# fn run(program: Vec<BpfInsn>) -> ferranet::Result<()> {
// Compile the expression with `tcpdump -dd '<expr>'`, a BPF-assembler crate, or by hand —
// ferranet accepts an already-compiled program, the same way it stays out of packet parsing.
let (_tx, rx) = Channel::builder("eth0").filter(program).build_sync()?;

// Optional: make the filter unremovable for the rest of the process's life.
rx.lock_filter()?;
# Ok(())
# }

The ordering guarantee: the socket is created with protocol zero (reception disabled), the filter is attached, and only then is the requested protocol bound. Every frame you can observe has passed the filter — no unfiltered frame can queue in the gap, and opening the channel never waits for a live receive queue to drain. detach_filter removes the program later (unless lock_filter was called), and the same controls exist on AsyncReceiver. See the filter module docs (src/filter.rs).

Permissions #

Opening an AF_PACKET socket requires the CAP_NET_RAW capability. For local use:

# Grant the capability to a built binary:
sudo setcap cap_net_raw+ep ./target/debug/examples/sniff

# Or run inside an unprivileged user + network namespace:
unshare --user --map-root-user --net ./your-program

Testing #

Unit tests need no privileges:

cargo test

Property tests (proptest) cover the pure parsing/validation surfaces — MAC parsing round-trips, ring-geometry invariants, snap-length derivation, and the TPACKET_V3 block parser's correctness — and run as part of cargo test.

Fuzzing (cargo-fuzz/libFuzzer) hammers the block parser — the one place ferranet does pointer reads with bounds checks over variable input — with coverage-guided garbage, including out-of-range offsets and adversarial frame counts:

cargo install cargo-fuzz
cargo +nightly fuzz run parse_block          # see fuzz/

Miri checks the pure-memory unsafe for undefined behaviour, out-of-bounds, and provenance violations — chiefly the block parser's read_unaligned/offset math and frame construction, driven over plain heap buffers:

cargo +nightly miri test --lib

Miri cannot interpret syscalls, so the FFI paths (sockets, mmap, PACKET_*, AF_XDP, interface enumeration) are #[ignore]d under Miri and covered by the veth/dummy/hw tests instead.

For deterministic, privilege-free testing of packet handling, the dummy backend gives you a real Sender/Receiver pair wired to in-memory FIFO queues instead of a NIC (a parity to libpnet's dummy backend, and usable by downstream code the same way):

let mut net = ferranet::dummy::channel()?;
net.inject.inject(frame_bytes);              // queue a frame to be received
let block = net.rx.recv_block()?;            // ... and receive it
net.tx.send(other_frame)?;                   // send a frame ...
assert_eq!(net.drain.try_recv().unwrap(), other_frame); // ... and read what was sent
# Ok::<(), ferranet::Error>(())

It is backed by a pipe for readiness, so it works with the blocking API, poll, and the async API alike. See tests/dummy.rs for the full suite (send/receive ordering, idle-blocking, injected errors, end-of-stream).

End-to-end tests use a veth pair and are #[ignore]d by default. Run them inside an unprivileged namespace, which provides CAP_NET_RAW without root. Build first (the namespace has no network, so compilation must happen outside it), then run:

cargo test --test veth --no-run
unshare --user --map-root-user --net \
    env RUSTC_WRAPPER= cargo test --test veth -- --ignored --test-threads=1

To exercise real hardware, the hw suite (also #[ignore]d) runs roundtrip, VLAN, RX-timestamp, and fanout-distribution checks against two cabled ports you name via the environment:

cargo test --test hw --no-run
sudo FERRANET_HW_IFACE_A=enp1s0f0 FERRANET_HW_IFACE_B=enp1s0f1 \
    ./target/debug/deps/hw-<hash> --ignored --test-threads=1

It skips cleanly when those vars are unset, so cargo test stays green everywhere.

Low-power / embedded hardware #

On constrained devices (small ARM SoCs, little RAM, small caches, single-queue NICs at low packet rates) the goal is less memory moved, smaller footprint, fewer wakeups, less CPU per frame — not peak Mpps. ferranet has several knobs for this:

use ferranet::{Channel, RingConfig};

let (mut tx, mut rx) = Channel::builder("eth0")
    // Small rings (~256 KiB vs the 8 MiB default) stay cache-resident and cut RAM ~32×.
    .rx_ring(RingConfig::small().snaplen(128))   // capture only headers
    .build_sync()?;
# Ok::<(), ferranet::Error>(())
  • RingConfig::small() — a ~256 KiB RX ring instead of 8 MiB. Ample at low rates and keeps the ring hot in L2.
  • RingConfig::snaplen(n) — for header-only monitoring, captures exactly the first n bytes per frame. The kernel truncates its copy into the ring, so far less memory/bandwidth is used and many more frames pack per block; Frame::wire_len() still reports the true length. The single biggest lever for header-parsing agents. (A TPACKET_V3 ring packs variable-sized frames, so the cap is enforced through the socket filter: with a ChannelBuilder::filter program attached, that program's accepting returns are capped to n — a smaller user cap wins, rejections and branches are untouched — and detaching it later keeps the cap.)
  • Lazy frame metadata — timestamp()/vlan()/packet_type() are decoded on access for ring-captured frames, so a loop that only reads frame.data() pays nothing for them.
  • Sync-only build — depend with default-features = false to drop Tokio: smaller binary, no async reactor, fewer threads. The blocking build_sync() API is all you need for a capture loop.
  • Wakeup vs latency — raise RingConfig { retire_blk_tov_ms, .. } (default 60 ms) to wake less often under light traffic (lower power), or lower it for snappier delivery.
  • One core, pinned — on a single-queue NIC use a single channel (no PACKET_FANOUT) and pin the capture thread to a core; build with -C target-cpu=<soc> for the target.

Detecting dropped packets #

For all-packets capture, the thing that loses data is the ring overflowing — so drop detection is first-class:

let block = rx.recv_block()?;
if block.is_losing() {                 // zero-syscall, inline: the kernel flagged drops
    let s = rx.stats()?;               // exact, cumulative counts (and clears the flag)
    eprintln!("dropped {} packets, {} ring freezes", s.dropped, s.freezes);
}
# Ok::<(), ferranet::Error>(())
  • Block::is_losing() — reads the TP_STATUS_LOSING bit the kernel sets on a block when it has dropped packets. No syscall, checkable every receive.
  • Receiver::stats() — monotonic cumulative received / dropped / freezes since the channel opened (ferranet accumulates the kernel's reset-on-read counter for you). Reading it also clears the losing flag, so the pattern is: is_losing() tells you that you're dropping, stats() tells you how much.

Benchmarking #

Performance is a primary goal, so the crate ships Criterion benchmarks that produce statistically-sampled results plus an HTML report and SVG plots under target/criterion/. Run everything with scripts/bench.sh, or individually:

cargo bench --bench parse                                   # privilege-free parse hot loop
cargo bench --bench throughput --no-run                     # build outside the namespace…
unshare --user --map-root-user --net env RUSTC_WRAPPER= cargo bench --bench throughput   # …run inside it
# open target/criterion/report/index.html

Headline numbers on a veth pair, including a same-harness comparison against libpnet's real datalink channel (pnet_datalink 0.35). Full results, methodology, and honest caveats in BENCHMARKS.md:

  • RX: ferranet's zero-copy ring is ~3× libpnet (1.90 vs 0.61 Mpps at 64 B), drops nothing under overload, and clears 20+ Gbit/s single-core at MTU (libpnet ~7). Even ferranet's basic backend beats libpnet ~1.8× (libpnet polls per packet).
  • TX: ferranet ~1.45× libpnet (0.68 vs 0.47 Mpps); over veth all backends are forwarding-bound, so the ring's batched-flush win is partly masked and widens on a real NIC.
  • PACKET_FANOUT distributes perfectly evenly across N receivers (e.g. [942, 940, 942, 945] k for N=4), parallelizing RX across cores. Aggregate scaling needs a multi-queue NIC; a single-queue veth caps the demo.
  • Next tier is AF_XDP (~10–20× over AF_PACKET), shipped as the experimental xdp feature behind the same boundary; not yet benchmarked here.

License #

MIT OR Apache-2.0.