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 dummy BPF programs on non-Linux systems.
Structs§
- Op
- A dummy implementation of BPF operation for non-Linux systems.
- Prog
- A dummy implementation of BPF program for non-Linux systems.
Traits§
- BpfFilter
Attachable - Trait for types that can have BPF filters attached.
Functions§
- attach_
filter - Attaches a BPF filter program to a socket (dummy implementation).
- detach_
filter - Detaches any BPF filter program from a socket (dummy implementation).
- lock_
filter - Locks the BPF filter on a socket (dummy implementation).