pub mod ffi;
pub use ffi::ifaces;
pub use ffi::temporary_ipv6_addresses;
#[cfg(any(test, target_os = "linux", target_os = "android"))]
pub(crate) fn parse_proc_if_inet6(text: &str) -> Vec<::std::net::Ipv6Addr> {
const IFA_F_TEMPORARY: u32 = 0x01;
text.lines()
.filter_map(|line| {
let fields: Vec<&str> = line.split_whitespace().collect();
let (address, flags) = (fields.first()?, fields.get(4)?);
if address.len() != 32 {
return None;
}
let address = u128::from_str_radix(address, 16).ok()?;
let flags = u32::from_str_radix(flags, 16).ok()?;
(flags & IFA_F_TEMPORARY != 0).then(|| ::std::net::Ipv6Addr::from(address))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn proc_if_inet6_lines_flagged_temporary_are_the_temporary_addresses() {
let text = "\
00000000000000000000000000000001 01 80 10 80 lo
fe80000000000000021122fffe334455 02 40 20 80 eth0
2a0012340000000102112233aabbccdd 02 40 00 100 eth0
2a001234000000014d2f1a2b3c4d5e6f 02 40 00 01 eth0
2a001234000000019a8b7c6d5e4f3a2b 02 40 00 21 eth0
";
assert_eq!(
parse_proc_if_inet6(text),
vec![
"2a00:1234:0:1:4d2f:1a2b:3c4d:5e6f"
.parse::<::std::net::Ipv6Addr>()
.unwrap(),
"2a00:1234:0:1:9a8b:7c6d:5e4f:3a2b".parse().unwrap(),
]
);
}
#[test]
fn windows_marks_no_address_temporary() {
let result = temporary_ipv6_addresses();
if cfg!(windows) {
assert!(
matches!(&result, Err(e) if e.kind() == std::io::ErrorKind::Unsupported),
"{result:?}"
);
}
}
#[test]
fn the_temporary_addresses_the_system_reports_are_among_its_interface_addresses() {
let temporary = match temporary_ipv6_addresses() {
Ok(temporary) => temporary,
Err(e) if e.kind() == std::io::ErrorKind::Unsupported => {
if cfg!(any(target_os = "linux", target_os = "macos")) {
panic!("the flags are read on this system: {e}");
}
return;
}
Err(e) => panic!("temporary_ipv6_addresses failed: {e}"),
};
let all: Vec<::std::net::IpAddr> = ifaces()
.unwrap()
.into_iter()
.filter_map(|i| i.addr.map(|a| a.ip()))
.collect();
for address in &temporary {
assert!(
all.contains(&::std::net::IpAddr::V6(*address)),
"{address} is not an interface address"
);
assert!(!address.is_loopback() && !address.is_unicast_link_local());
}
}
}
#[derive(PartialEq, Eq, Debug, Clone)]
#[non_exhaustive]
pub enum NextHop {
Broadcast(::std::net::SocketAddr),
Destination(::std::net::SocketAddr),
}
#[derive(PartialEq, Eq, Debug, Clone)]
#[non_exhaustive]
pub enum Kind {
Packet,
Link,
Ipv4,
Ipv6,
Unknow(i32),
}
#[derive(Debug, Clone)]
pub struct Interface {
pub name: String,
pub kind: Kind,
pub addr: Option<::std::net::SocketAddr>,
pub mask: Option<::std::net::SocketAddr>,
pub hop: Option<NextHop>,
}