Skip to main content

cross_platform_dump/
cross_platform_dump.rs

1//! Cross-platform packet dumper — captures and prints Ethernet frames.
2//!
3//! # Platform Support
4//! - Linux: AF_PACKET (requires root)
5//! - macOS: BPF (requires root)
6//! - Windows: NPcap (requires NPcap installed + Administrator)
7//!
8//! # Usage
9//! ```sh
10//! sudo cargo run --example cross_platform_dump -- eth0
11//! cargo run --example cross_platform_dump          # auto-detect first non-loopback
12//! ```
13
14use std::time::Duration;
15use wireforge_io::{list_interfaces, DefaultL2Reader, traits::L2Reader};
16
17fn main() -> Result<(), Box<dyn std::error::Error>> {
18    let ifname = std::env::args().nth(1).unwrap_or_else(|| {
19        list_interfaces()
20            .ok()
21            .and_then(|ifaces| ifaces.into_iter().find(|i| !i.is_loopback && i.is_up).map(|i| i.name))
22            .unwrap_or_else(|| "lo".into())
23    });
24
25    println!("Opening {} ...", ifname);
26    let mut rx = DefaultL2Reader::new(&ifname)?;
27    rx.set_timeout(Some(Duration::from_secs(1)))?;
28
29    println!("Listening on {} (Ctrl+C to stop)...\n", ifname);
30    for i in 0..10 {
31        match rx.recv() {
32            Ok(eth) => {
33                println!("#{}: {} → {}  EtherType={:?}  len={}",
34                    i + 1,
35                    mac_hex(&eth.src_mac()),
36                    mac_hex(&eth.dst_mac()),
37                    eth.ethertype(),
38                    eth.payload().len() + 14,
39                );
40            }
41            Err(wireforge_io::IoError::Timeout) => continue,
42            Err(e) => { eprintln!("Error: {e}"); break; }
43        }
44    }
45    Ok(())
46}
47
48fn mac_hex(mac: &[u8; 6]) -> String {
49    format!("{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5])
50}