Skip to main content

maestro_rs/
interface.rs

1use std::{
2    fmt,
3    net::{IpAddr, Ipv4Addr, Ipv6Addr},
4    str::FromStr,
5};
6
7use getifaddrs::{Address, InterfaceFlags, getifaddrs, if_nametoindex};
8
9use crate::{Error, Result};
10
11/// A local network interface and the addresses assigned to it.
12///
13/// This is a snapshot taken when the value is created. It does not track
14/// addresses added or removed afterwards.
15///
16/// # Examples
17///
18/// ```no_run
19/// use maestro_rs::NetworkInterface;
20///
21/// let eth0: NetworkInterface = "eth0".parse()?;
22/// println!("{eth0}: {:?} {:?}", eth0.ipv4(), eth0.ipv6());
23///
24/// // Portable way to get the loopback interface:
25/// let lo = NetworkInterface::loopback()?;
26/// # Ok::<(), maestro_rs::Error>(())
27/// ```
28///
29/// Because it implements [`FromStr`], it can be used directly as a
30/// [`clap`](https://docs.rs/clap) argument with `value_parser!(NetworkInterface)`.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct NetworkInterface {
33    name: String,
34    index: u32,
35    ipv4: Vec<Ipv4Addr>,
36    ipv6: Vec<Ipv6Addr>,
37    mac: Option<[u8; 6]>,
38    loopback: bool,
39    alias: Option<String>,
40}
41
42impl NetworkInterface {
43    /// Looks up an interface by its system name (e.g. `"eth0"`, `"lo0"`).
44    ///
45    /// On Windows the friendly name shown in the control panel (e.g.
46    /// `"Ethernet"`, matched case-insensitively) is accepted as well as the
47    /// system name (e.g. `"ethernet_32768"`). See [`alias`](Self::alias).
48    ///
49    /// # Errors
50    ///
51    /// - [`Error::InvalidInterfaceName`] if `name` is empty or contains a NUL byte.
52    /// - [`Error::InterfaceNotFound`] if no such interface exists.
53    /// - [`Error::Io`] if the system interface list cannot be read.
54    pub fn from_name(name: &str) -> Result<Self> {
55        if name.trim().is_empty() || name.contains('\0') {
56            return Err(Error::InvalidInterfaceName(name.to_owned()));
57        }
58
59        Self::list()?
60            .into_iter()
61            .find(|iface| {
62                iface.name == name
63                    || iface
64                        .alias
65                        .as_deref()
66                        .is_some_and(|alias| alias.eq_ignore_ascii_case(name))
67            })
68            .ok_or_else(|| Error::InterfaceNotFound(name.to_owned()))
69    }
70
71    /// The first loopback interface: `lo` on Linux, `lo0` on macOS and BSD,
72    /// `loopback_0` on Windows.
73    ///
74    /// # Errors
75    ///
76    /// - [`Error::InterfaceNotFound`] if the system has no loopback interface.
77    /// - [`Error::Io`] if the system interface list cannot be read.
78    pub fn loopback() -> Result<Self> {
79        Self::list()?
80            .into_iter()
81            .find(Self::is_loopback)
82            .ok_or_else(|| Error::InterfaceNotFound("loopback".to_owned()))
83    }
84
85    /// Lists every network interface on the system, in the order the OS reports them.
86    ///
87    /// # Errors
88    ///
89    /// Returns [`Error::Io`] if the system interface list cannot be read.
90    pub fn list() -> Result<Vec<Self>> {
91        let mut out: Vec<Self> = Vec::new();
92        for entry in getifaddrs()? {
93            let pos = match out.iter().position(|i| i.name == entry.name) {
94                Some(pos) => pos,
95                None => {
96                    let index = match entry.index {
97                        Some(index) => index,
98                        None => if_nametoindex(&entry.name)?,
99                    };
100                    #[cfg_attr(not(windows), expect(unused_mut))]
101                    let mut iface = Self::empty(entry.name, index);
102                    #[cfg(windows)]
103                    {
104                        iface.alias = Some(entry.description).filter(|d| !d.is_empty());
105                    }
106                    out.push(iface);
107                    out.len() - 1
108                }
109            };
110            out[pos].absorb(entry.address, entry.flags);
111        }
112        Ok(out)
113    }
114
115    /// The system name, e.g. `"eth0"`.
116    #[must_use]
117    pub fn name(&self) -> &str {
118        &self.name
119    }
120
121    /// The OS interface index (used as the IPv6 scope ID).
122    #[must_use]
123    pub fn index(&self) -> u32 {
124        self.index
125    }
126
127    /// IPv4 addresses assigned to the interface.
128    #[must_use]
129    pub fn ipv4(&self) -> &[Ipv4Addr] {
130        &self.ipv4
131    }
132
133    /// IPv6 addresses assigned to the interface.
134    #[must_use]
135    pub fn ipv6(&self) -> &[Ipv6Addr] {
136        &self.ipv6
137    }
138
139    /// All IPv4 then IPv6 addresses assigned to the interface.
140    pub fn addrs(&self) -> impl Iterator<Item = IpAddr> + '_ {
141        let v4 = self.ipv4.iter().copied().map(IpAddr::V4);
142        let v6 = self.ipv6.iter().copied().map(IpAddr::V6);
143        v4.chain(v6)
144    }
145
146    /// The hardware (MAC) address, if the interface has one.
147    ///
148    /// Loopback and tunnel interfaces typically have none.
149    #[must_use]
150    pub fn mac(&self) -> Option<[u8; 6]> {
151        self.mac
152    }
153
154    /// The Windows friendly name (e.g. `"Ethernet"`). Always `None` on other platforms.
155    #[must_use]
156    pub fn alias(&self) -> Option<&str> {
157        self.alias.as_deref()
158    }
159
160    /// Whether this is a loopback interface.
161    #[must_use]
162    pub fn is_loopback(&self) -> bool {
163        self.loopback
164    }
165
166    fn empty(name: String, index: u32) -> Self {
167        Self {
168            name,
169            index,
170            ipv4: Vec::new(),
171            ipv6: Vec::new(),
172            mac: None,
173            loopback: false,
174            alias: None,
175        }
176    }
177
178    fn absorb(&mut self, address: Address, flags: InterfaceFlags) {
179        self.loopback |= flags.contains(InterfaceFlags::LOOPBACK);
180        match address {
181            Address::V4(v4) => self.ipv4.push(v4.address),
182            Address::V6(v6) => self.ipv6.push(v6.address),
183            // Some platforms report an all-zero MAC for interfaces without one.
184            Address::Mac(mac) if mac != [0; 6] => self.mac = Some(mac),
185            Address::Mac(_) => {}
186        }
187    }
188}
189
190impl FromStr for NetworkInterface {
191    type Err = Error;
192
193    fn from_str(name: &str) -> Result<Self> {
194        Self::from_name(name)
195    }
196}
197
198impl fmt::Display for NetworkInterface {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        f.pad(&self.name)
201    }
202}
203
204#[cfg(test)]
205pub(crate) mod tests {
206    use super::*;
207
208    pub(crate) fn loopback() -> NetworkInterface {
209        NetworkInterface::loopback().expect("system has a loopback interface")
210    }
211
212    #[test]
213    fn list_contains_loopback_with_localhost() {
214        let lo = loopback();
215        assert!(lo.ipv4().contains(&Ipv4Addr::LOCALHOST));
216    }
217
218    #[test]
219    fn from_name_matches_list_entry() {
220        let lo = loopback();
221        let by_name = NetworkInterface::from_name(lo.name()).unwrap();
222        assert_eq!(by_name, lo);
223    }
224
225    #[test]
226    fn empty_name_is_invalid() {
227        assert!(matches!(
228            "  ".parse::<NetworkInterface>(),
229            Err(Error::InvalidInterfaceName(_))
230        ));
231    }
232
233    #[test]
234    fn numeric_name_is_not_treated_as_index() {
235        assert!(matches!(
236            NetworkInterface::from_name("4242"),
237            Err(Error::InterfaceNotFound(_))
238        ));
239    }
240
241    #[test]
242    fn unknown_name_is_not_found() {
243        assert!(matches!(
244            NetworkInterface::from_name("maestro-nope0"),
245            Err(Error::InterfaceNotFound(_))
246        ));
247    }
248}