Skip to main content

packet_dump/
packet_dump.rs

1//! Example: capture and dump packets from a network interface.
2//!
3//! Linux only. Usage: `cargo run --example packet_dump -- <interface>`
4//!
5//! ```sh
6//! sudo cargo run --example packet_dump -- eth0
7//! ```
8
9#[cfg(target_os = "linux")]
10fn main() -> Result<(), Box<dyn std::error::Error>> {
11    use wireforge_io::{L2Receiver, IoError};
12
13    let ifname = std::env::args().nth(1).unwrap_or_else(|| "lo".into());
14    let mut rx = L2Receiver::new(&ifname)?;
15    println!("Listening on {}...", ifname);
16
17    loop {
18        match rx.recv() {
19            Ok(eth) => {
20                println!(
21                    "{} -> {}  EtherType={:?}  payload={} bytes",
22                    hex_mac(&eth.src_mac()),
23                    hex_mac(&eth.dst_mac()),
24                    eth.ethertype(),
25                    eth.payload().len(),
26                );
27            }
28            Err(IoError::Timeout) => continue,
29            Err(e) => {
30                eprintln!("Error: {}", e);
31                break;
32            }
33        }
34    }
35    Ok(())
36}
37
38fn hex_mac(mac: &[u8; 6]) -> String {
39    format!(
40        "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
41        mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]
42    )
43}
44
45#[cfg(not(target_os = "linux"))]
46fn main() {
47    eprintln!("packet_dump requires Linux (AF_PACKET sockets).");
48}