default_net/gateway/
mod.rs

1#[cfg(any(target_os = "openbsd", target_os = "freebsd", target_os = "netbsd"))]
2pub(crate) mod unix;
3
4#[cfg(any(target_os = "macos", target_os = "ios"))]
5pub(crate) mod macos;
6
7#[cfg(any(target_os = "linux", target_os = "android"))]
8pub(crate) mod linux;
9
10#[cfg(feature = "serde")]
11use serde::{Deserialize, Serialize};
12
13use crate::interface::{self, Interface};
14use crate::mac::MacAddr;
15use std::net::{IpAddr, Ipv4Addr};
16
17/// Structure of default Gateway information
18#[derive(Clone, Eq, PartialEq, Hash, Debug)]
19#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
20pub struct Gateway {
21    /// MAC address of Gateway
22    pub mac_addr: MacAddr,
23    /// IP address of Gateway
24    pub ip_addr: IpAddr,
25}
26
27impl Gateway {
28    /// Construct a new Gateway instance
29    pub fn new() -> Gateway {
30        Gateway {
31            mac_addr: MacAddr::zero(),
32            ip_addr: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
33        }
34    }
35}
36
37/// Get default Gateway
38pub fn get_default_gateway() -> Result<Gateway, String> {
39    let local_ip: IpAddr = match interface::get_local_ipaddr() {
40        Some(local_ip) => local_ip,
41        None => return Err(String::from("Local IP address not found")),
42    };
43    let interfaces: Vec<Interface> = interface::get_interfaces();
44    for iface in interfaces {
45        match local_ip {
46            IpAddr::V4(local_ipv4) => {
47                if iface.ipv4.iter().any(|x| x.addr == local_ipv4) {
48                    if let Some(gateway) = iface.gateway {
49                        return Ok(gateway);
50                    }
51                }
52            }
53            IpAddr::V6(local_ipv6) => {
54                if iface.ipv6.iter().any(|x| x.addr == local_ipv6) {
55                    if let Some(gateway) = iface.gateway {
56                        return Ok(gateway);
57                    }
58                }
59            }
60        }
61    }
62    Err(String::from("Default Gateway not found"))
63}
64
65#[cfg(any(
66    target_os = "linux",
67    target_os = "android",
68    target_os = "openbsd",
69    target_os = "freebsd",
70    target_os = "netbsd"
71))]
72fn send_udp_packet() -> Result<(), String> {
73    use std::net::UdpSocket;
74    let buf = [0u8; 0];
75    let socket = match UdpSocket::bind("0.0.0.0:0") {
76        Ok(s) => s,
77        Err(e) => return Err(format!("Failed to create UDP socket {}", e)),
78    };
79    let dst: &str = "1.1.1.1:80";
80    match socket.set_ttl(1) {
81        Ok(_) => (),
82        Err(e) => return Err(format!("Failed to set TTL {}", e)),
83    }
84    match socket.send_to(&buf, dst) {
85        Ok(_) => (),
86        Err(e) => return Err(format!("Failed to send data {}", e)),
87    }
88    Ok(())
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94    #[test]
95    fn test_default_gateway() {
96        println!("{:?}", get_default_gateway());
97    }
98}