use pree::routing::{RouteEvent, RouteMonitor, RoutingTable};
use std::net::IpAddr;
use std::str::FromStr;
use std::thread;
use std::time::Duration;
fn main() -> pree::Result<()> {
let routes = RoutingTable::get()?;
println!("Current Routing Table:");
for route in &routes.routes {
println!("\nRoute:");
println!(" Destination: {}", route.destination);
println!(
" Gateway: {}",
route
.gateway
.map_or_else(|| "None".to_string(), |g| g.to_string())
);
println!(" Interface: {}", route.interface);
println!(" Metric: {}", route.metric);
}
if let Some(default_gateway) = routes.default_gateway() {
println!("\nDefault Gateway:");
println!(" IP: {}", default_gateway.destination);
println!(" Interface: {}", default_gateway.interface);
}
let test_ips = [
"8.8.8.8", "192.168.1.1", "10.0.0.1", ];
println!("\nRoute Lookups:");
for ip_str in test_ips {
if let Ok(ip) = IpAddr::from_str(ip_str) {
if let Some(route) = routes.find_route(ip) {
println!("\nRoute for {ip}:");
println!(
" Via: {}",
route
.gateway
.map_or_else(|| "None".to_string(), |g| g.to_string())
);
println!(" Interface: {}", route.interface);
} else {
println!("\nNo route found for {ip}");
}
}
}
let mut monitor = RouteMonitor::new()?;
monitor.on_route_change(|event| match event {
RouteEvent::Added(route) => {
println!("\nNew route added:");
println!(" Destination: {}", route.destination);
println!(
" Gateway: {}",
route
.gateway
.map_or_else(|| "None".to_string(), |g| g.to_string())
);
}
RouteEvent::Removed(route) => {
println!("\nRoute removed:");
println!(" Destination: {}", route.destination);
println!(
" Gateway: {}",
route
.gateway
.map_or_else(|| "None".to_string(), |g| g.to_string())
);
}
RouteEvent::Changed(old_route, new_route) => {
println!("\nRoute changed:");
println!(" Destination: {}", new_route.destination);
println!(
" Old Gateway: {}",
old_route
.gateway
.map_or_else(|| "None".to_string(), |g| g.to_string())
);
println!(
" New Gateway: {}",
new_route
.gateway
.map_or_else(|| "None".to_string(), |g| g.to_string())
);
}
})?;
monitor.start()?;
thread::sleep(Duration::from_secs(30));
monitor.stop();
Ok(())
}