1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use std::net::IpAddr;
use crate::interface::{MacAddr, Interface};
use crate::os;
#[derive(Clone, Debug)]
pub struct Gateway {
pub mac_addr: MacAddr,
pub ip_addr: IpAddr,
}
pub fn get_default_gateway() -> Result<Gateway, String> {
let local_ip: IpAddr = match os::get_local_ipaddr(){
Some(local_ip) => local_ip,
None => return Err(String::from("Local IP address not found")),
};
let interfaces: Vec<Interface> = os::interfaces();
for iface in interfaces {
match local_ip {
IpAddr::V4(local_ipv4) => {
if iface.ipv4.contains(&local_ipv4) {
if let Some(gateway) = iface.gateway {
return Ok(gateway);
}
}
},
IpAddr::V6(local_ipv6) => {
if iface.ipv6.contains(&local_ipv6) {
if let Some(gateway) = iface.gateway {
return Ok(gateway);
}
}
},
}
}
Err(String::from("Default Gateway not found"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_gateway() {
println!("{:?}", get_default_gateway());
}
}