Skip to main content

labstream_net/
netif.rs

1//! Cross-platform network interface and neighbor enumeration.
2//!
3//! liblsl enumerates interfaces with `GetAdaptersAddresses` on Windows and
4//! `getifaddrs` on Linux and macOS (`src/netinterfaces.cpp:21-114`). This
5//! module gives the same interface list on Unix and Windows, plus the IPv4
6//! directed broadcast address and local ARP neighbors for fallback discovery
7//! (`docs/discovery.md`).
8
9use std::net::Ipv4Addr;
10
11/// One local IPv4 interface address.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Ipv4Interface {
14    /// Operating system name of the interface, or an index label on Windows.
15    pub name: String,
16    /// Local IPv4 address.
17    pub addr: Ipv4Addr,
18    /// Subnet prefix length (0 to 32).
19    pub prefix_len: u8,
20    /// Directed subnet broadcast address, when the prefix is below 31.
21    pub broadcast: Option<Ipv4Addr>,
22    /// Interface index.
23    pub ifindex: u32,
24    /// True when the interface is up.
25    pub is_up: bool,
26    /// True when the interface is loopback.
27    pub is_loopback: bool,
28    /// True when the interface supports multicast.
29    pub supports_multicast: bool,
30}
31
32impl Ipv4Interface {
33    /// Host addresses in this subnet, excluding network, broadcast, and self.
34    ///
35    /// Returns an empty list for loopback, down interfaces, or subnets larger
36    /// than `/24` (`prefix_len < 24`). A corporate `/16` is never swept.
37    pub fn subnet_peers(&self) -> Vec<Ipv4Addr> {
38        if !self.is_up || self.is_loopback || self.prefix_len < 24 || self.prefix_len >= 31 {
39            return Vec::new();
40        }
41        let mask = prefix_to_mask(self.prefix_len);
42        let ip = u32::from(self.addr);
43        let net = ip & mask;
44        let bcast = net | !mask;
45        let mut out = Vec::new();
46        for host in (net + 1)..bcast {
47            if host != ip {
48                out.push(Ipv4Addr::from(host));
49            }
50        }
51        out
52    }
53}
54
55/// Convert a prefix length (0 to 32) to a big-endian IPv4 bitmask.
56pub fn prefix_to_mask(prefix_len: u8) -> u32 {
57    if prefix_len == 0 {
58        0
59    } else if prefix_len >= 32 {
60        u32::MAX
61    } else {
62        !0u32 << (32 - prefix_len)
63    }
64}
65
66/// Compute the directed broadcast address from an IPv4 address and prefix.
67pub fn directed_broadcast(addr: Ipv4Addr, prefix_len: u8) -> Option<Ipv4Addr> {
68    if addr.is_loopback() || prefix_len == 0 || prefix_len >= 31 {
69        return None;
70    }
71    let mask = prefix_to_mask(prefix_len);
72    Some(Ipv4Addr::from(u32::from(addr) | !mask))
73}
74
75/// Every active IPv4 interface on this machine.
76pub fn local_ipv4_interfaces() -> Vec<Ipv4Interface> {
77    platform_ipv4_interfaces()
78}
79
80/// Every local IPv4 address on this machine, for multicast binds and sends.
81pub fn local_ipv4_addresses() -> Vec<Ipv4Addr> {
82    let mut out = Vec::new();
83    for iface in local_ipv4_interfaces() {
84        if iface.is_up && !iface.addr.is_broadcast() && !out.contains(&iface.addr) {
85            out.push(iface.addr);
86        }
87    }
88    out
89}
90
91/// Every interface index on this machine, with zero at the front.
92pub fn local_interface_indexes() -> Vec<u32> {
93    platform_interface_indexes()
94}
95
96/// Local IPv4 neighbors from the operating system ARP table.
97pub fn local_ipv4_neighbors() -> Vec<Ipv4Addr> {
98    platform_ipv4_neighbors()
99}
100
101/// Parse Linux `/proc/net/arp` text into valid unicast IPv4 neighbors.
102pub fn parse_proc_arp(text: &str) -> Vec<Ipv4Addr> {
103    let mut out = Vec::new();
104    for line in text.lines().skip(1) {
105        let cols: Vec<&str> = line.split_whitespace().collect();
106        if cols.len() < 4 {
107            continue;
108        }
109        // Flags column: 0x0 means incomplete.
110        if cols[2] == "0x0" {
111            continue;
112        }
113        // Hardware address column: all zeroes means unresolved.
114        if cols[3] == "00:00:00:00:00:00" {
115            continue;
116        }
117        if let Ok(ip) = cols[0].parse::<Ipv4Addr>() {
118            if !ip.is_loopback()
119                && !ip.is_multicast()
120                && !ip.is_broadcast()
121                && !ip.is_unspecified()
122                && !out.contains(&ip)
123            {
124                out.push(ip);
125            }
126        }
127    }
128    out
129}
130
131#[cfg(unix)]
132fn platform_ipv4_interfaces() -> Vec<Ipv4Interface> {
133    use std::ffi::CStr;
134    let mut out = Vec::new();
135    #[allow(unsafe_code)]
136    {
137        let mut ifap: *mut libc::ifaddrs = std::ptr::null_mut();
138        // SAFETY: `getifaddrs` allocates a linked list of `ifaddrs` entries and
139        // writes the head pointer into `ifap`. We free it with `freeifaddrs`.
140        if unsafe { libc::getifaddrs(&mut ifap) } != 0 {
141            return out;
142        }
143        let mut cur = ifap;
144        while !cur.is_null() {
145            // SAFETY: `cur` is a valid non-null node from `getifaddrs`.
146            let ifa = unsafe { &*cur };
147            cur = ifa.ifa_next;
148            if ifa.ifa_addr.is_null() {
149                continue;
150            }
151            // SAFETY: `ifa_addr` is non-null and holds a valid `sockaddr`.
152            let family = unsafe { (*ifa.ifa_addr).sa_family } as i32;
153            if family != libc::AF_INET {
154                continue;
155            }
156            // SAFETY: `sa_family == AF_INET`, so `ifa_addr` points to `sockaddr_in`.
157            let sin = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_in) };
158            let addr = Ipv4Addr::from(u32::from_be(sin.sin_addr.s_addr));
159            let prefix_len = if !ifa.ifa_netmask.is_null() {
160                // SAFETY: `ifa_netmask` is non-null for an AF_INET entry.
161                let m = unsafe { &*(ifa.ifa_netmask as *const libc::sockaddr_in) };
162                u32::from_be(m.sin_addr.s_addr).leading_ones() as u8
163            } else {
164                32
165            };
166            let flags = ifa.ifa_flags as i32;
167            let is_up = (flags & libc::IFF_UP) != 0;
168            let is_loopback = (flags & libc::IFF_LOOPBACK) != 0 || addr.is_loopback();
169            let supports_multicast = (flags & libc::IFF_MULTICAST) != 0;
170            let name = if !ifa.ifa_name.is_null() {
171                // SAFETY: `ifa_name` is a NUL-terminated C string.
172                unsafe { CStr::from_ptr(ifa.ifa_name) }
173                    .to_string_lossy()
174                    .into_owned()
175            } else {
176                String::new()
177            };
178            // SAFETY: `ifa_name` is either null or a valid C string.
179            let ifindex = if !ifa.ifa_name.is_null() {
180                unsafe { libc::if_nametoindex(ifa.ifa_name) }
181            } else {
182                0
183            };
184            let broadcast = if is_up && !is_loopback {
185                directed_broadcast(addr, prefix_len)
186            } else {
187                None
188            };
189            out.push(Ipv4Interface {
190                name,
191                addr,
192                prefix_len,
193                broadcast,
194                ifindex,
195                is_up,
196                is_loopback,
197                supports_multicast,
198            });
199        }
200        // SAFETY: `ifap` was returned by `getifaddrs` above.
201        unsafe { libc::freeifaddrs(ifap) };
202    }
203    out
204}
205
206#[cfg(unix)]
207fn platform_interface_indexes() -> Vec<u32> {
208    let mut out = vec![0u32];
209    #[allow(unsafe_code)]
210    {
211        let mut ifap: *mut libc::ifaddrs = std::ptr::null_mut();
212        // SAFETY: `getifaddrs` allocates a linked list freed with `freeifaddrs`.
213        if unsafe { libc::getifaddrs(&mut ifap) } == 0 {
214            let mut cur = ifap;
215            while !cur.is_null() {
216                // SAFETY: `cur` is a valid non-null node from `getifaddrs`.
217                let ifa = unsafe { &*cur };
218                cur = ifa.ifa_next;
219                if ifa.ifa_name.is_null() {
220                    continue;
221                }
222                let flags = ifa.ifa_flags as i32;
223                if (flags & libc::IFF_UP) == 0 {
224                    continue;
225                }
226                // SAFETY: `ifa_name` is a NUL-terminated C string.
227                let idx = unsafe { libc::if_nametoindex(ifa.ifa_name) };
228                if idx != 0 && !out.contains(&idx) {
229                    out.push(idx);
230                }
231            }
232            // SAFETY: `ifap` was returned by `getifaddrs` above.
233            unsafe { libc::freeifaddrs(ifap) };
234        }
235    }
236    out
237}
238
239#[cfg(unix)]
240fn platform_ipv4_neighbors() -> Vec<Ipv4Addr> {
241    if let Ok(text) = std::fs::read_to_string("/proc/net/arp") {
242        return parse_proc_arp(&text);
243    }
244    Vec::new()
245}
246
247#[cfg(windows)]
248mod win_iphlp {
249    /// `MIB_IPADDRROW` from `ipmib.h`. Fixed 24 bytes on x86, x64, and ARM64.
250    #[repr(C)]
251    #[derive(Clone, Copy)]
252    pub struct MibIpAddrRow {
253        pub dw_addr: u32,
254        pub dw_index: u32,
255        pub dw_mask: u32,
256        pub dw_bcast_addr: u32,
257        pub dw_reasm_size: u32,
258        pub unused1: u16,
259        pub w_type: u16,
260    }
261
262    /// `MIB_IPNETROW` from `ipmib.h`. Fixed 24 bytes on x86, x64, and ARM64.
263    #[repr(C)]
264    #[derive(Clone, Copy)]
265    pub struct MibIpNetRow {
266        pub dw_index: u32,
267        pub dw_phys_addr_len: u32,
268        pub b_phys_addr: [u8; 8],
269        pub dw_addr: u32,
270        pub dw_type: u32,
271    }
272
273    pub const ERROR_INSUFFICIENT_BUFFER: u32 = 122;
274    pub const NO_ERROR: u32 = 0;
275    pub const MIB_IPNET_TYPE_DYNAMIC: u32 = 3;
276    pub const MIB_IPNET_TYPE_STATIC: u32 = 4;
277
278    #[link(name = "iphlpapi")]
279    extern "system" {
280        pub fn GetIpAddrTable(p_ip_addr_table: *mut u8, pdw_size: *mut u32, b_order: i32) -> u32;
281        pub fn GetIpNetTable(p_ip_net_table: *mut u8, pdw_size: *mut u32, b_order: i32) -> u32;
282    }
283}
284
285#[cfg(windows)]
286fn platform_ipv4_interfaces() -> Vec<Ipv4Interface> {
287    use win_iphlp::*;
288    let mut out = Vec::new();
289    #[allow(unsafe_code)]
290    {
291        let mut size: u32 = 0;
292        // SAFETY: query required buffer size with null output pointer.
293        let rc = unsafe { GetIpAddrTable(std::ptr::null_mut(), &mut size, 0) };
294        if rc != ERROR_INSUFFICIENT_BUFFER || size < 4 {
295            return out;
296        }
297        let mut buf = vec![0u8; size as usize];
298        // SAFETY: `buf` has at least `size` writable bytes.
299        let rc = unsafe { GetIpAddrTable(buf.as_mut_ptr(), &mut size, 0) };
300        if rc != NO_ERROR || size < 4 {
301            return out;
302        }
303        let count = u32::from_ne_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;
304        let row_size = std::mem::size_of::<MibIpAddrRow>();
305        let avail = (buf.len().saturating_sub(4)) / row_size;
306        let n = count.min(avail);
307        for i in 0..n {
308            let offset = 4 + i * row_size;
309            // SAFETY: `offset + row_size <= buf.len()` and `MibIpAddrRow` is `Copy`.
310            let row = unsafe {
311                std::ptr::read_unaligned(buf.as_ptr().add(offset) as *const MibIpAddrRow)
312            };
313            let addr = Ipv4Addr::from(u32::from_be(row.dw_addr));
314            if addr.is_unspecified() {
315                continue;
316            }
317            let mask = u32::from_be(row.dw_mask);
318            let prefix_len = mask.leading_ones() as u8;
319            let is_loopback = addr.is_loopback();
320            let broadcast = if !is_loopback {
321                directed_broadcast(addr, prefix_len)
322            } else {
323                None
324            };
325            out.push(Ipv4Interface {
326                name: format!("if{}", row.dw_index),
327                addr,
328                prefix_len,
329                broadcast,
330                ifindex: row.dw_index,
331                is_up: true,
332                is_loopback,
333                supports_multicast: !is_loopback,
334            });
335        }
336    }
337    out
338}
339
340#[cfg(windows)]
341fn platform_interface_indexes() -> Vec<u32> {
342    let mut out = vec![0u32];
343    for iface in platform_ipv4_interfaces() {
344        if iface.ifindex != 0 && !out.contains(&iface.ifindex) {
345            out.push(iface.ifindex);
346        }
347    }
348    out
349}
350
351#[cfg(windows)]
352fn platform_ipv4_neighbors() -> Vec<Ipv4Addr> {
353    use win_iphlp::*;
354    let mut out = Vec::new();
355    #[allow(unsafe_code)]
356    {
357        let mut size: u32 = 0;
358        // SAFETY: query required buffer size with null output pointer.
359        let rc = unsafe { GetIpNetTable(std::ptr::null_mut(), &mut size, 0) };
360        if rc != ERROR_INSUFFICIENT_BUFFER || size < 4 {
361            return out;
362        }
363        let mut buf = vec![0u8; size as usize];
364        // SAFETY: `buf` has at least `size` writable bytes.
365        let rc = unsafe { GetIpNetTable(buf.as_mut_ptr(), &mut size, 0) };
366        if rc != NO_ERROR || size < 4 {
367            return out;
368        }
369        let count = u32::from_ne_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;
370        let row_size = std::mem::size_of::<MibIpNetRow>();
371        let avail = (buf.len().saturating_sub(4)) / row_size;
372        let n = count.min(avail);
373        for i in 0..n {
374            let offset = 4 + i * row_size;
375            // SAFETY: `offset + row_size <= buf.len()` and `MibIpNetRow` is `Copy`.
376            let row =
377                unsafe { std::ptr::read_unaligned(buf.as_ptr().add(offset) as *const MibIpNetRow) };
378            if row.dw_type != MIB_IPNET_TYPE_DYNAMIC && row.dw_type != MIB_IPNET_TYPE_STATIC {
379                continue;
380            }
381            let ip = Ipv4Addr::from(u32::from_be(row.dw_addr));
382            if !ip.is_loopback()
383                && !ip.is_multicast()
384                && !ip.is_broadcast()
385                && !ip.is_unspecified()
386                && !out.contains(&ip)
387            {
388                out.push(ip);
389            }
390        }
391    }
392    out
393}
394
395#[cfg(not(any(unix, windows)))]
396fn platform_ipv4_interfaces() -> Vec<Ipv4Interface> {
397    Vec::new()
398}
399
400#[cfg(not(any(unix, windows)))]
401fn platform_interface_indexes() -> Vec<u32> {
402    vec![0]
403}
404
405#[cfg(not(any(unix, windows)))]
406fn platform_ipv4_neighbors() -> Vec<Ipv4Addr> {
407    Vec::new()
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413
414    #[test]
415    fn subnet_peers_covers_slash_24_and_skips_larger_subnets() {
416        let make = |addr: Ipv4Addr, prefix_len: u8, is_loopback: bool| Ipv4Interface {
417            name: "eth0".to_string(),
418            addr,
419            prefix_len,
420            broadcast: directed_broadcast(addr, prefix_len),
421            ifindex: 2,
422            is_up: true,
423            is_loopback,
424            supports_multicast: true,
425        };
426        let lan = make(Ipv4Addr::new(192, 168, 2, 10), 24, false);
427        assert_eq!(lan.broadcast, Some(Ipv4Addr::new(192, 168, 2, 255)));
428        let peers = lan.subnet_peers();
429        assert_eq!(peers.len(), 253);
430        assert!(peers.contains(&Ipv4Addr::new(192, 168, 2, 1)));
431        assert!(peers.contains(&Ipv4Addr::new(192, 168, 2, 254)));
432        assert!(!peers.contains(&Ipv4Addr::new(192, 168, 2, 10)));
433        assert!(!peers.contains(&Ipv4Addr::new(192, 168, 2, 0)));
434        assert!(!peers.contains(&Ipv4Addr::new(192, 168, 2, 255)));
435
436        // A /16 corporate subnet must not be swept.
437        let big = make(Ipv4Addr::new(10, 0, 1, 5), 16, false);
438        assert_eq!(big.broadcast, Some(Ipv4Addr::new(10, 0, 255, 255)));
439        assert!(big.subnet_peers().is_empty());
440
441        // Loopback is never swept.
442        let lo = make(Ipv4Addr::LOCALHOST, 8, true);
443        assert!(lo.subnet_peers().is_empty());
444
445        // A /30 has two usable hosts: 1 peer.
446        let p2p = make(Ipv4Addr::new(10, 77, 0, 1), 30, false);
447        assert_eq!(p2p.subnet_peers(), vec![Ipv4Addr::new(10, 77, 0, 2)]);
448    }
449
450    #[test]
451    fn parse_proc_arp_keeps_valid_unicast_entries_only() {
452        let sample = "\
453IP address       HW type     Flags       HW address            Mask     Device
454192.168.2.1      0x1         0x2         aa:bb:cc:dd:ee:01     *        wlan0
455192.168.2.208    0x1         0x2         aa:bb:cc:dd:ee:02     *        wlan0
456192.168.2.99     0x1         0x0         00:00:00:00:00:00     *        wlan0
457127.0.0.1        0x1         0x2         00:00:00:00:00:01     *        lo
458224.0.0.183      0x1         0x2         01:00:5e:00:00:b7     *        wlan0
459";
460        assert_eq!(
461            parse_proc_arp(sample),
462            vec![
463                Ipv4Addr::new(192, 168, 2, 1),
464                Ipv4Addr::new(192, 168, 2, 208),
465            ]
466        );
467    }
468
469    #[test]
470    fn local_ipv4_interfaces_finds_loopback() {
471        let list = local_ipv4_interfaces();
472        assert!(
473            list.iter().any(|i| i.addr == Ipv4Addr::LOCALHOST),
474            "expected loopback in {list:?}"
475        );
476    }
477}