| Crates.io | async-pcap |
| lib.rs | async-pcap |
| version | 0.1.6 |
| created_at | 2025-10-11 02:33:40.429471+00 |
| updated_at | 2025-10-12 11:56:56.36744+00 |
| description | An asynchronous implementation of pcap. |
| homepage | https://github.com/LorenzoLeonardo/async-pcap |
| repository | https://github.com/LorenzoLeonardo/async-pcap |
| max_upload_size | |
| id | 1877768 |
| size | 27,506 |
async-pcap is a Rust library that provides an asynchronous wrapper around pcap packet captures. It allows you to capture network packets in a non-blocking, async context using Tokio. Internally, it spawns a dedicated thread to poll packets and delivers them via an asynchronous channel.
pcap::Capture<Active>.Vec<u8>) with packet metadata.AsyncCapture::new() and next_packet().await.use async_pcap::{AsyncCapture, Capture, Device};
use tokio::runtime::Runtime;
fn main() {
let rt = Runtime::new().unwrap();
rt.block_on(async {
// Open the network device
let device = Device::lookup().unwrap().unwrap();
let cap = Capture::from_device(device)
.unwrap()
.promisc(true)
.snaplen(65535)
.timeout(500)
.immediate_mode(true)
.open()
.unwrap();
// Create the async capture and handle
let (async_cap, handle) = AsyncCapture::new(cap);
// Clone the handle to stop from another task
let handle_clone = handle.clone();
// Spawn a task to stop capture after 5 seconds
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
handle_clone.stop(); // This sends the Stop signal
println!("Capture stopped from another task");
});
// Read packets asynchronously
while let Some(packet) = async_cap.next_packet().await {
match packet {
Ok(packet) => {
println!("Packet: {}", packet.data.len());
}
Err(e) => {
println!("{e}");
}
}
}
println!("Capture loop exited cleanly");
});
}
AsyncCapture internally spawns a dedicated thread for polling packets.Mutex and UnboundedReceiver for async packet delivery.