Expand description
Rust library for attaching BPF filters to sockets.
This library provides a simple interface for creating and attaching Berkeley Packet Filter (BPF) programs to sockets on Linux systems. On non-Linux systems, it provides dummy implementations that maintain API compatibility but don’t perform any actual filtering.
BPF is a technology used in the Linux kernel to filter network packets at the socket level. It allows applications to efficiently filter packets in kernel space before they’re delivered to user space, reducing unnecessary data copies and improving performance.
§Features
- Create and attach BPF filters to sockets
- Detach filters when no longer needed
- Lock filters to prevent unauthorized modification
- Simple macro syntax for defining BPF programs
- Cross-platform API (real implementation on Linux, dummy on other platforms)
§Basic Usage
use bpf::{bpfprog, BpfFilterAttachable};
use std::net::UdpSocket;
fn main() -> std::io::Result<()> {
// Create a socket
let socket = UdpSocket::bind("0.0.0.0:0")?;
// Create a BPF program that only accepts UDP packets on port 53 (DNS)
let filter = bpfprog!(2,
0x30 0 0 0x00000011, // Load byte at position 17 (IP protocol)
0x15 0 1 0x00000011 // If UDP (17), accept, else drop
);
// Attach the filter to the socket using the trait
socket.attach_filter(filter)?;
// Later, detach if needed
socket.detach_filter()?;
Ok(())
}
Macros§
- bpfprog
- Macro for creating BPF programs with a more concise syntax.
Structs§
- Op
- Represents a single BPF instruction (operation).
- Prog
- Represents a complete BPF program, consisting of a sequence of operations.
Traits§
- BpfFilter
Attachable - Trait for types that can have BPF filters attached.
Functions§
- attach_
filter - Attaches a BPF filter program to a socket.
- detach_
filter - Detaches any BPF filter program from a socket.
- lock_
filter - Locks the BPF filter on a socket to prevent it from being replaced.