getifs/
mtu.rs

1use core::net::IpAddr;
2use std::{
3  io,
4  net::{Ipv4Addr, Ipv6Addr},
5};
6
7use super::interfaces;
8
9fn interface_not_found_for_ip() -> io::Error {
10  io::Error::new(io::ErrorKind::Other, "interface not found")
11}
12
13/// Get the MTU of the given [`IpAddr`].
14///
15/// ## Example
16///
17/// ```rust
18/// use getifs::get_ip_mtu;
19///
20/// let mtu = get_ip_mtu("127.0.0.1".parse().unwrap()).unwrap();
21/// println!("MTU: {}", mtu);
22/// ```
23pub fn get_ip_mtu(ip: IpAddr) -> io::Result<u32> {
24  interfaces().and_then(|ifis| {
25    for iface in ifis {
26      match iface.addrs_by_filter(|addr| ip.eq(addr)) {
27        Ok(addrs) => {
28          if !addrs.is_empty() {
29            return Ok(iface.mtu());
30          }
31        }
32        Err(_) => continue,
33      }
34    }
35
36    Err(interface_not_found_for_ip())
37  })
38}
39
40/// Get the MTU of the given [`Ipv4Addr`].
41///
42/// ## Example
43///
44/// ```rust
45/// use std::net::Ipv4Addr;
46/// use getifs::get_ipv4_mtu;
47///
48/// let mtu = get_ipv4_mtu(Ipv4Addr::LOCALHOST).unwrap();
49/// println!("MTU: {}", mtu);
50/// ```
51pub fn get_ipv4_mtu(ip: Ipv4Addr) -> io::Result<u32> {
52  interfaces().and_then(|ifis| {
53    for iface in ifis {
54      match iface.ipv4_addrs_by_filter(|addr| ip.eq(addr)) {
55        Ok(addrs) => {
56          if !addrs.is_empty() {
57            return Ok(iface.mtu());
58          }
59        }
60        Err(_) => continue,
61      }
62    }
63
64    Err(interface_not_found_for_ip())
65  })
66}
67
68/// Get the MTU of the given [`Ipv6Addr`].
69///
70/// ## Example
71///
72/// ```rust
73/// use std::net::Ipv6Addr;
74/// use getifs::get_ipv6_mtu;
75///
76/// let mtu = get_ipv6_mtu(Ipv6Addr::LOCALHOST).unwrap();
77/// println!("MTU: {}", mtu);
78/// ```
79pub fn get_ipv6_mtu(ip: Ipv6Addr) -> io::Result<u32> {
80  interfaces().and_then(|ifis| {
81    for iface in ifis {
82      match iface.ipv6_addrs_by_filter(|addr| ip.eq(addr)) {
83        Ok(addrs) => {
84          if !addrs.is_empty() {
85            return Ok(iface.mtu());
86          }
87        }
88        Err(_) => continue,
89      }
90    }
91
92    Err(interface_not_found_for_ip())
93  })
94}