Skip to content

Commit 006a55f

Browse files
authored
Merge pull request #155 from dignifiedquire/feat/ipv6-addr-flags
2 parents 2ed33ca + 447dd3d commit 006a55f

16 files changed

Lines changed: 333 additions & 31 deletions

File tree

‎examples/list_interfaces.rs‎

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,37 @@ fn main() {
2626
}
2727
println!("\tIPv4: {:?}", interface.ipv4);
2828

29-
// Print the IPv6 addresses with the scope ID after them as a suffix
30-
let ipv6_strs: Vec<String> = interface
31-
.ipv6
32-
.iter()
33-
.zip(interface.ipv6_scope_ids)
34-
.map(|(ipv6, scope_id)| format!("{:?}%{}", ipv6, scope_id))
35-
.collect();
36-
println!("\tIPv6: [{}]", ipv6_strs.join(", "));
29+
// Print IPv6 addresses with scope ID and per-address flags
30+
for (i, ipv6) in interface.ipv6.iter().enumerate() {
31+
let scope_id = interface.ipv6_scope_ids.get(i).copied().unwrap_or(0);
32+
let flags = interface
33+
.ipv6_addr_flags
34+
.get(i)
35+
.copied()
36+
.unwrap_or_default();
37+
let mut flag_strs = Vec::new();
38+
if flags.deprecated {
39+
flag_strs.push("deprecated");
40+
}
41+
if flags.temporary {
42+
flag_strs.push("temporary");
43+
}
44+
if flags.tentative {
45+
flag_strs.push("tentative");
46+
}
47+
if flags.duplicated {
48+
flag_strs.push("duplicated");
49+
}
50+
if flags.permanent {
51+
flag_strs.push("permanent");
52+
}
53+
let flag_str = if flag_strs.is_empty() {
54+
String::new()
55+
} else {
56+
format!(" [{}]", flag_strs.join(", "))
57+
};
58+
println!("\tIPv6: {:?}%{}{}", ipv6, scope_id, flag_str);
59+
}
3760

3861
println!("\tTransmit Speed: {:?}", interface.transmit_speed);
3962
println!("\tReceive Speed: {:?}", interface.receive_speed);

‎src/interface/interface.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use crate::interface::ipv6_addr_flags::Ipv6AddrFlags;
12
use crate::interface::state::OperState;
23
use crate::ipnet::{Ipv4Net, Ipv6Net};
34
use crate::net::ip::{is_global_ip, is_global_ipv4, is_global_ipv6};
@@ -60,6 +61,8 @@ pub struct Interface {
6061
/// zone indexes. A value can be `0` when no scope is needed or when the platform did not
6162
/// provide one.
6263
pub ipv6_scope_ids: Vec<u32>,
64+
/// Per-address IPv6 flags, aligned with entries in `Interface::ipv6`.
65+
pub ipv6_addr_flags: Vec<Ipv6AddrFlags>,
6366
/// Raw interface flags.
6467
///
6568
/// Bit meanings are platform-specific.
@@ -125,6 +128,7 @@ impl Interface {
125128
ipv4: Vec::new(),
126129
ipv6: Vec::new(),
127130
ipv6_scope_ids: Vec::new(),
131+
ipv6_addr_flags: Vec::new(),
128132
flags: 0,
129133
oper_state: OperState::Unknown,
130134
transmit_speed: None,

‎src/interface/ipv6_addr_flags.rs‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
//! Per-address IPv6 state flags, normalized across platforms.
2+
3+
/// State flags for a single IPv6 address.
4+
///
5+
/// All fields default to `false` when the platform does not provide the
6+
/// corresponding information.
7+
///
8+
/// Flags are collected from platform-specific sources:
9+
///
10+
/// - **Linux/Android**: netlink `IFA_FLAGS` attribute (`IFA_F_*` from [`<linux/if_addr.h>`])
11+
/// - **macOS/iOS**: `SIOCGIFAFLAG_IN6` ioctl (`IN6_IFF_*` from [`<netinet6/in6_var.h>`][xnu])
12+
/// - **FreeBSD/OpenBSD/NetBSD**: `SIOCGIFAFLAG_IN6` ioctl (`IN6_IFF_*` from [`<netinet6/in6_var.h>`][freebsd])
13+
/// - **Windows**: [`NL_DAD_STATE`] and [`NL_SUFFIX_ORIGIN`] from `IP_ADAPTER_UNICAST_ADDRESS`
14+
///
15+
/// [`<linux/if_addr.h>`]: https://github.com/torvalds/linux/blob/master/include/uapi/linux/if_addr.h
16+
/// [xnu]: https://github.com/apple-oss-distributions/xnu/blob/main/bsd/netinet6/in6_var.h
17+
/// [freebsd]: https://github.com/freebsd/freebsd-src/blob/main/sys/netinet6/in6_var.h
18+
/// [`NL_DAD_STATE`]: https://learn.microsoft.com/en-us/windows/win32/api/nldef/ne-nldef-nl_dad_state
19+
/// [`NL_SUFFIX_ORIGIN`]: https://learn.microsoft.com/en-us/windows/win32/api/nldef/ne-nldef-nl_suffix_origin
20+
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
21+
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22+
pub struct Ipv6AddrFlags {
23+
/// Preferred lifetime expired; should not be used for new connections.
24+
///
25+
/// Sourced from `IFA_F_DEPRECATED` (Linux), `IN6_IFF_DEPRECATED` (BSD),
26+
/// or `IpDadStateDeprecated` (Windows).
27+
pub deprecated: bool,
28+
/// Privacy address ([RFC 4941](https://datatracker.ietf.org/doc/html/rfc4941)).
29+
///
30+
/// Sourced from `IFA_F_TEMPORARY` (Linux), `IN6_IFF_TEMPORARY` (BSD),
31+
/// or `IpSuffixOriginRandom` (Windows).
32+
pub temporary: bool,
33+
/// Undergoing duplicate address detection.
34+
///
35+
/// Sourced from `IFA_F_TENTATIVE` (Linux), `IN6_IFF_TENTATIVE` (BSD),
36+
/// or `IpDadStateTentative` (Windows).
37+
pub tentative: bool,
38+
/// Duplicate address detection failed.
39+
///
40+
/// Sourced from `IFA_F_DADFAILED` (Linux), `IN6_IFF_DUPLICATED` (BSD),
41+
/// or `IpDadStateDuplicate` (Windows).
42+
pub duplicated: bool,
43+
/// Manually configured, not from SLAAC.
44+
///
45+
/// Sourced from `IFA_F_PERMANENT` (Linux). Not available on BSD or Windows.
46+
pub permanent: bool,
47+
}
48+
49+
// Platform dispatch for `get_ipv6_addr_flags`, called from `unix_interfaces()`.
50+
51+
#[cfg(target_vendor = "apple")]
52+
pub(crate) use crate::os::darwin::ipv6_addr_flags::*;
53+
54+
#[cfg(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
55+
pub(crate) use crate::os::bsd::ipv6_addr_flags::*;
56+
57+
// On Linux/Android flags come from netlink; this is only reached via the
58+
// `unix_interfaces()` fallback when netlink is unavailable.
59+
#[cfg(any(target_os = "linux", target_os = "android"))]
60+
pub(crate) fn get_ipv6_addr_flags(_ifname: &str, _addr: &std::net::Ipv6Addr) -> Ipv6AddrFlags {
61+
Ipv6AddrFlags::default()
62+
}

‎src/interface/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
pub mod flags;
22
pub mod interface;
3+
pub mod ipv6_addr_flags;
34
pub mod mtu;
45
pub mod state;
56
pub mod types;

‎src/os/android/interface.rs‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,17 @@ fn push_ipv4(v: &mut Vec<Ipv4Net>, add: (Ipv4Addr, u8)) {
2323
}
2424
}
2525

26-
fn push_ipv6(v: &mut Vec<Ipv6Net>, add: (Ipv6Addr, u8)) {
26+
fn push_ipv6(v: &mut Vec<Ipv6Net>, add: (Ipv6Addr, u8)) -> bool {
2727
if v.iter()
2828
.any(|n| n.addr() == add.0 && n.prefix_len() == add.1)
2929
{
30-
return;
30+
return false;
3131
}
3232
if let Ok(net) = Ipv6Net::new(add.0, add.1) {
3333
v.push(net);
34+
return true;
3435
}
36+
false
3537
}
3638

3739
#[inline]
@@ -87,6 +89,7 @@ pub fn interfaces() -> Vec<Interface> {
8789
ipv4: Vec::new(),
8890
ipv6: Vec::new(),
8991
ipv6_scope_ids: Vec::new(),
92+
ipv6_addr_flags: Vec::new(),
9093
flags: r.flags,
9194
oper_state: OperState::from_if_flags(r.flags),
9295
transmit_speed: None,
@@ -104,9 +107,14 @@ pub fn interfaces() -> Vec<Interface> {
104107
for (a, p) in r.ipv4 {
105108
push_ipv4(&mut iface.ipv4, (a, p));
106109
}
107-
for (a, p) in r.ipv6 {
108-
push_ipv6(&mut iface.ipv6, (a, p));
109-
iface.ipv6_scope_ids.push(calc_v6_scope_id(&a, iface.index));
110+
for (i, (a, p)) in r.ipv6.into_iter().enumerate() {
111+
if push_ipv6(&mut iface.ipv6, (a, p)) {
112+
iface.ipv6_scope_ids.push(calc_v6_scope_id(&a, iface.index));
113+
let raw = r.ipv6_addr_flags.get(i).copied().unwrap_or(0);
114+
iface
115+
.ipv6_addr_flags
116+
.push(crate::os::linux::ipv6_addr_flags::from_netlink_flags(raw));
117+
}
110118
}
111119

112120
ifaces.push(iface);

‎src/os/android/netlink.rs‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use crate::stats::counters::InterfaceStats;
33
use netlink_packet_core::{NLM_F_DUMP, NLM_F_REQUEST, NetlinkMessage, NetlinkPayload};
44
use netlink_packet_route::{
55
RouteNetlinkMessage,
6-
address::{AddressAttribute, AddressMessage},
6+
address::{AddressAttribute, AddressFlags, AddressMessage},
77
link::{LinkAttribute, LinkMessage},
88
};
99
use netlink_sys::{Socket, SocketAddr, protocols::NETLINK_ROUTE};
@@ -236,17 +236,25 @@ fn name_from_link(link: &LinkMessage) -> Option<String> {
236236
None
237237
}
238238

239-
fn ip_from_addr(addr: &AddressMessage) -> Option<(IpAddr, u8)> {
239+
fn ip_from_addr(addr: &AddressMessage) -> Option<(IpAddr, u8, u32)> {
240240
let pfx = addr.header.prefix_len;
241+
let mut ip_out = None;
242+
let mut flags: Option<AddressFlags> = None;
241243
for nla in &addr.attributes {
242244
match nla {
243245
AddressAttribute::Local(ip) | AddressAttribute::Address(ip) => {
244-
return Some((*ip, pfx));
246+
ip_out = Some(*ip);
247+
}
248+
AddressAttribute::Flags(f) => {
249+
flags = Some(*f);
245250
}
246251
_ => {}
247252
}
248253
}
249-
None
254+
let addr_flags = flags
255+
.map(|f| f.bits())
256+
.unwrap_or(addr.header.flags.bits() as u32);
257+
ip_out.map(|ip| (ip, pfx, addr_flags))
250258
}
251259

252260
#[cfg(feature = "gateway")]
@@ -385,6 +393,7 @@ pub struct IfRow {
385393
pub mac: Option<[u8; 6]>,
386394
pub ipv4: Vec<(Ipv4Addr, u8)>,
387395
pub ipv6: Vec<(Ipv6Addr, u8)>,
396+
pub ipv6_addr_flags: Vec<u32>,
388397
pub flags: u32,
389398
pub mtu: Option<u32>,
390399
pub if_type: InterfaceType,
@@ -413,6 +422,7 @@ pub fn collect_interfaces() -> io::Result<Vec<IfRow>> {
413422
mac,
414423
ipv4: vec![],
415424
ipv6: vec![],
425+
ipv6_addr_flags: vec![],
416426
flags,
417427
mtu: mtu_nl,
418428
if_type,
@@ -423,11 +433,14 @@ pub fn collect_interfaces() -> io::Result<Vec<IfRow>> {
423433

424434
for a in addrs {
425435
let idx = a.header.index as u32;
426-
if let Some((ip, pfx)) = ip_from_addr(&a) {
436+
if let Some((ip, pfx, addr_flags)) = ip_from_addr(&a) {
427437
if let Some(row) = base.get_mut(&idx) {
428438
match ip {
429439
IpAddr::V4(v4) => row.ipv4.push((v4, pfx)),
430-
IpAddr::V6(v6) => row.ipv6.push((v6, pfx)),
440+
IpAddr::V6(v6) => {
441+
row.ipv6.push((v6, pfx));
442+
row.ipv6_addr_flags.push(addr_flags);
443+
}
431444
}
432445
}
433446
}

‎src/os/bsd/ipv6_addr_flags.rs‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
use std::net::Ipv6Addr;
2+
3+
use crate::interface::ipv6_addr_flags::Ipv6AddrFlags;
4+
5+
// <netinet6/in6_var.h> — not yet in `libc`.
6+
const SIOCGIFAFLAG_IN6: libc::c_ulong = 0xC1206949;
7+
const IN6_IFF_TENTATIVE: u32 = 0x02;
8+
const IN6_IFF_DUPLICATED: u32 = 0x04;
9+
const IN6_IFF_DEPRECATED: u32 = 0x10;
10+
const IN6_IFF_TEMPORARY: u32 = 0x80;
11+
12+
// `libc` does not expose `in6_ifreq` on FreeBSD/OpenBSD/NetBSD.
13+
#[repr(C)]
14+
struct In6Ifreq {
15+
ifr_name: [u8; libc::IFNAMSIZ],
16+
ifr_addr: libc::sockaddr_in6,
17+
ifr_flags: libc::c_int,
18+
}
19+
20+
pub(crate) fn get_ipv6_addr_flags(ifname: &str, addr: &Ipv6Addr) -> Ipv6AddrFlags {
21+
unsafe {
22+
let fd = libc::socket(libc::AF_INET6, libc::SOCK_DGRAM, 0);
23+
if fd < 0 {
24+
return Ipv6AddrFlags::default();
25+
}
26+
27+
let mut req: In6Ifreq = std::mem::zeroed();
28+
29+
let name_bytes = ifname.as_bytes();
30+
let copy_len = name_bytes.len().min(libc::IFNAMSIZ - 1);
31+
std::ptr::copy_nonoverlapping(
32+
name_bytes.as_ptr(),
33+
req.ifr_name.as_mut_ptr().cast(),
34+
copy_len,
35+
);
36+
37+
req.ifr_addr.sin6_family = libc::AF_INET6 as libc::sa_family_t;
38+
req.ifr_addr.sin6_len = std::mem::size_of::<libc::sockaddr_in6>() as u8;
39+
req.ifr_addr.sin6_addr.s6_addr = addr.octets();
40+
41+
let ret = libc::ioctl(fd, SIOCGIFAFLAG_IN6, &mut req);
42+
libc::close(fd);
43+
44+
if ret < 0 {
45+
return Ipv6AddrFlags::default();
46+
}
47+
48+
let raw = req.ifr_flags as u32;
49+
50+
Ipv6AddrFlags {
51+
deprecated: raw & IN6_IFF_DEPRECATED != 0,
52+
temporary: raw & IN6_IFF_TEMPORARY != 0,
53+
tentative: raw & IN6_IFF_TENTATIVE != 0,
54+
duplicated: raw & IN6_IFF_DUPLICATED != 0,
55+
permanent: false,
56+
}
57+
}
58+
}

‎src/os/bsd/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
pub mod flags;
22
pub mod interface;
3+
pub mod ipv6_addr_flags;
34
pub mod mtu;
45
#[cfg(feature = "gateway")]
56
pub mod route;

‎src/os/darwin/ipv6_addr_flags.rs‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
use std::net::Ipv6Addr;
2+
3+
use crate::interface::ipv6_addr_flags::Ipv6AddrFlags;
4+
5+
// <netinet6/in6_var.h> — not yet in `libc`.
6+
const SIOCGIFAFLAG_IN6: libc::c_ulong = 0xC1206949;
7+
const IN6_IFF_TENTATIVE: u32 = 0x02;
8+
const IN6_IFF_DUPLICATED: u32 = 0x04;
9+
const IN6_IFF_DEPRECATED: u32 = 0x10;
10+
const IN6_IFF_TEMPORARY: u32 = 0x80;
11+
12+
pub(crate) fn get_ipv6_addr_flags(ifname: &str, addr: &Ipv6Addr) -> Ipv6AddrFlags {
13+
unsafe {
14+
let fd = libc::socket(libc::AF_INET6, libc::SOCK_DGRAM, 0);
15+
if fd < 0 {
16+
return Ipv6AddrFlags::default();
17+
}
18+
19+
let mut req: libc::in6_ifreq = std::mem::zeroed();
20+
21+
let name_bytes = ifname.as_bytes();
22+
let copy_len = name_bytes.len().min(libc::IFNAMSIZ - 1);
23+
std::ptr::copy_nonoverlapping(
24+
name_bytes.as_ptr(),
25+
req.ifr_name.as_mut_ptr().cast(),
26+
copy_len,
27+
);
28+
29+
req.ifr_ifru.ifru_addr.sin6_family = libc::AF_INET6 as libc::sa_family_t;
30+
req.ifr_ifru.ifru_addr.sin6_len =
31+
std::mem::size_of::<libc::sockaddr_in6>() as libc::c_uchar;
32+
req.ifr_ifru.ifru_addr.sin6_addr.s6_addr = addr.octets();
33+
34+
let ret = libc::ioctl(fd, SIOCGIFAFLAG_IN6, &mut req);
35+
libc::close(fd);
36+
37+
if ret < 0 {
38+
return Ipv6AddrFlags::default();
39+
}
40+
41+
let raw = req.ifr_ifru.ifru_flags6 as u32;
42+
43+
Ipv6AddrFlags {
44+
deprecated: raw & IN6_IFF_DEPRECATED != 0,
45+
temporary: raw & IN6_IFF_TEMPORARY != 0,
46+
tentative: raw & IN6_IFF_TENTATIVE != 0,
47+
duplicated: raw & IN6_IFF_DUPLICATED != 0,
48+
permanent: false,
49+
}
50+
}
51+
}

‎src/os/darwin/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
pub mod flags;
2+
pub mod ipv6_addr_flags;
23
pub mod mtu;
34
#[cfg(feature = "gateway")]
45
pub mod route;

0 commit comments

Comments
 (0)