use std::net::Ipv4Addr;
use crate::NetError;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LanScore {
PrivateClassC,
PrivateClassA,
PrivateClassB,
OtherRoutable,
}
impl LanScore {
fn rank(self) -> u8 {
match self {
LanScore::PrivateClassC => 4,
LanScore::PrivateClassA => 3,
LanScore::PrivateClassB => 2,
LanScore::OtherRoutable => 1,
}
}
}
const VIRTUAL_IFACE_NAME_HINTS: &[&str] = &[
"clash",
"wintun",
"tun",
"tap",
"utun",
"vpn",
"wireguard",
"wg",
"tailscale",
"zerotier",
"hyper-v",
"vethernet",
"vmware",
"virtualbox",
"vbox",
"loopback",
"wsl",
"docker",
];
pub(super) fn in_cidr(ip: Ipv4Addr, base: [u8; 4], prefix: u8) -> bool {
let ip_bits = u32::from_be_bytes(ip.octets());
let base_bits = u32::from_be_bytes(base);
if prefix == 0 {
return true;
}
let mask: u32 = u32::MAX << (32 - prefix);
(ip_bits & mask) == (base_bits & mask)
}
fn classify_lan_ipv4(ip: Ipv4Addr) -> Option<LanScore> {
if ip.is_loopback() || ip.is_link_local() || ip.is_unspecified() || ip.is_broadcast() {
return None;
}
if in_cidr(ip, [198, 18, 0, 0], 15) || in_cidr(ip, [100, 64, 0, 0], 10) {
return None;
}
if in_cidr(ip, [192, 168, 0, 0], 16) {
return Some(LanScore::PrivateClassC);
}
if in_cidr(ip, [10, 0, 0, 0], 8) {
return Some(LanScore::PrivateClassA);
}
if in_cidr(ip, [172, 16, 0, 0], 12) {
return Some(LanScore::PrivateClassB);
}
Some(LanScore::OtherRoutable)
}
pub(super) fn looks_like_virtual_iface(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
#[cfg(target_os = "linux")]
if ["veth", "virbr", "br-", "cni", "flannel"]
.iter()
.any(|prefix| lower.starts_with(prefix))
{
return true;
}
VIRTUAL_IFACE_NAME_HINTS
.iter()
.any(|hint| lower.contains(hint))
}
struct IfaceCandidate {
name: String,
ip: Ipv4Addr,
oper_up: bool,
is_p2p: bool,
}
fn pick_lan_ipv4_from(candidates: &[IfaceCandidate]) -> Option<Ipv4Addr> {
let mut best: Option<(u8, Ipv4Addr)> = None;
for c in candidates {
if !c.oper_up {
continue;
}
if c.is_p2p {
continue;
}
if looks_like_virtual_iface(&c.name) {
continue;
}
let Some(score) = classify_lan_ipv4(c.ip) else {
continue;
};
let rank = score.rank();
match best {
Some((best_rank, _)) if best_rank >= rank => {}
_ => best = Some((rank, c.ip)),
}
}
best.map(|(_, ip)| ip)
}
pub(crate) fn preferred_lan_ipv4() -> Result<Option<Ipv4Addr>, NetError> {
select_interface_address(enumerate_interfaces())
}
pub(super) fn enumerate_interfaces() -> std::io::Result<Vec<if_addrs::Interface>> {
if_addrs::get_if_addrs()
}
fn select_interface_address(
interfaces: std::io::Result<Vec<if_addrs::Interface>>,
) -> Result<Option<Ipv4Addr>, NetError> {
let ifaces = interfaces.map_err(NetError::from)?;
let mut candidates: Vec<IfaceCandidate> = Vec::new();
for iface in &ifaces {
let if_addrs::IfAddr::V4(v4) = &iface.addr else {
continue;
};
candidates.push(IfaceCandidate {
name: iface.name.clone(),
ip: v4.ip,
oper_up: iface.is_oper_up(),
is_p2p: iface.is_p2p(),
});
}
Ok(pick_lan_ipv4_from(&candidates))
}
#[cfg(test)]
mod tests {
use super::*;
fn cand(name: &str, ip: [u8; 4]) -> IfaceCandidate {
IfaceCandidate {
name: name.to_string(),
ip: Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]),
oper_up: true,
is_p2p: false,
}
}
#[test]
fn prefers_private_192_over_clash_tun() {
let ifaces = vec![
cand("Clash", [198, 18, 0, 1]),
cand("WLAN", [192, 168, 1, 5]),
];
assert_eq!(
pick_lan_ipv4_from(&ifaces),
Some(Ipv4Addr::new(192, 168, 1, 5))
);
}
#[test]
fn returns_none_when_only_virtual_or_invalid() {
let ifaces = vec![
cand("Loopback", [127, 0, 0, 1]),
cand("wintun-clash", [198, 18, 0, 1]),
cand("eth0", [169, 254, 3, 4]), ];
assert_eq!(pick_lan_ipv4_from(&ifaces), None);
}
#[test]
fn prefers_192_over_10() {
let ifaces = vec![cand("eth1", [10, 0, 0, 7]), cand("WLAN", [192, 168, 0, 9])];
assert_eq!(
pick_lan_ipv4_from(&ifaces),
Some(Ipv4Addr::new(192, 168, 0, 9))
);
}
#[test]
fn excludes_by_iface_name_even_if_subnet_looks_private() {
let ifaces = vec![
cand("VMware Network Adapter", [192, 168, 56, 1]),
cand("Ethernet", [192, 168, 1, 20]),
];
assert_eq!(
pick_lan_ipv4_from(&ifaces),
Some(Ipv4Addr::new(192, 168, 1, 20))
);
}
#[cfg(target_os = "linux")]
#[test]
fn linux_container_and_vm_interfaces_do_not_outrank_the_physical_lan() {
let physical_ip = Ipv4Addr::new(10, 1, 2, 3);
for name in [
"veth123abc",
"virbr0",
"br-a1b2c3d4e5f6",
"docker0",
"cni0",
"flannel.1",
"VETH123ABC",
] {
let ifaces = vec![
cand(name, [192, 168, 122, 1]),
cand("enp3s0", physical_ip.octets()),
];
assert_eq!(pick_lan_ipv4_from(&ifaces), Some(physical_ip), "{name}");
assert_eq!(pick_lan_ipv4_from(&ifaces[..1]), None, "{name}");
}
}
#[cfg(target_os = "linux")]
#[test]
fn linux_keeps_host_bridges_bonds_and_container_lan_interfaces() {
let lan_ip = Ipv4Addr::new(192, 168, 1, 20);
for name in ["br0", "bond0", "eth0", "enp3s0", "wlp2s0", "lan-veth"] {
let ifaces = vec![cand(name, lan_ip.octets())];
assert_eq!(pick_lan_ipv4_from(&ifaces), Some(lan_ip), "{name}");
}
}
#[cfg(not(target_os = "linux"))]
#[test]
fn linux_interface_prefixes_do_not_change_other_platforms() {
for name in [
"veth123abc",
"virbr0",
"br-a1b2c3d4e5f6",
"cni0",
"flannel.1",
] {
assert!(!looks_like_virtual_iface(name), "{name}");
}
}
#[test]
fn excludes_point_to_point_and_down() {
let mut p2p = cand("utun5", [192, 168, 9, 9]);
p2p.is_p2p = true;
let mut down = cand("Ethernet", [192, 168, 9, 10]);
down.oper_up = false;
let good = cand("WLAN", [192, 168, 9, 11]);
let ifaces = vec![p2p, down, good];
assert_eq!(
pick_lan_ipv4_from(&ifaces),
Some(Ipv4Addr::new(192, 168, 9, 11))
);
}
#[test]
fn excludes_cgnat_100_64() {
let ifaces = vec![
cand("tailscale0", [100, 100, 1, 1]),
cand("Ethernet", [10, 1, 2, 3]),
];
assert_eq!(
pick_lan_ipv4_from(&ifaces),
Some(Ipv4Addr::new(10, 1, 2, 3))
);
}
#[test]
fn cidr_boundaries() {
assert!(classify_lan_ipv4(Ipv4Addr::new(198, 19, 255, 1)).is_none());
assert_eq!(
classify_lan_ipv4(Ipv4Addr::new(198, 20, 0, 1)),
Some(LanScore::OtherRoutable)
);
assert_eq!(
classify_lan_ipv4(Ipv4Addr::new(172, 31, 0, 1)),
Some(LanScore::PrivateClassB)
);
assert_eq!(
classify_lan_ipv4(Ipv4Addr::new(172, 32, 0, 1)),
Some(LanScore::OtherRoutable)
);
}
}
#[cfg(test)]
mod fallible_query_tests {
use super::*;
#[test]
fn enumeration_failure_is_not_an_empty_address() -> Result<(), Box<dyn std::error::Error>> {
let failure = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "interface lookup");
if !matches!(
select_interface_address(Err(failure)),
Err(ref __classified_error_0) if matches!(__classified_error_0.kind(), crate::error::ErrorKind::Io))
{
return Err("interface enumeration failure was hidden".into());
}
Ok(())
}
#[test]
fn successful_empty_enumeration_has_no_address() -> Result<(), Box<dyn std::error::Error>> {
if select_interface_address(Ok(Vec::new()))?.is_some() {
return Err("empty interface enumeration invented an address".into());
}
Ok(())
}
}
#[cfg(test)]
mod source_retention_tests {
use super::*;
use std::error::Error;
#[test]
fn enumeration_error_retains_the_original_io_source() -> Result<(), Box<dyn Error>> {
let failure = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "interface lookup");
let error = select_interface_address(Err(failure))
.err()
.ok_or("enumeration unexpectedly succeeded")?;
if error.io_kind() != Some(std::io::ErrorKind::PermissionDenied)
|| error
.source()
.and_then(|source| source.downcast_ref::<std::io::Error>())
.is_none()
{
return Err("interface enumeration lost its original I/O source".into());
}
Ok(())
}
}