diff --git a/desktop/src/main.rs b/desktop/src/main.rs index f85bff5..51ce040 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -1049,7 +1049,7 @@ impl QftApp { pc_name: self.local_device.clone(), transport: "http-parallel-v2".into(), port: server.port, - endpoints: pairing::qr_endpoints(server.port, self.receive.direct_ap.is_some()), + endpoints: pairing::qr_endpoints(server.port, direct_ap.is_some()), wifi, direction: PairingDirection::Upload, file_name: None, @@ -1129,7 +1129,7 @@ impl QftApp { pc_name: self.local_device.clone(), transport: "http-download-v2".into(), port: server.port, - endpoints: pairing::qr_endpoints(server.port, self.send.direct_ap.is_some()), + endpoints: pairing::qr_endpoints(server.port, direct_ap.is_some()), wifi, direction: PairingDirection::Download, file_name: Some(file_name), diff --git a/desktop/src/pairing.rs b/desktop/src/pairing.rs index 0a2276e..0ffef90 100644 --- a/desktop/src/pairing.rs +++ b/desktop/src/pairing.rs @@ -226,6 +226,25 @@ pub fn qr_endpoints(port: u16, direct_ap_active: bool) -> Vec { endpoints } +/// 判断地址是否多半来自虚拟网卡。 +/// +/// 依据的是各家虚拟化产品的默认网段,且都以 `.1` 结尾(宿主机在虚拟网络里 +/// 通常是网关)。这只是启发式,因此调用方只降权、不丢弃。 +fn is_likely_virtual(ip: Ipv4Addr) -> bool { + let o = ip.octets(); + if o[3] != 1 { + return false; + } + match (o[0], o[1]) { + // VMware Workstation 常用 192.168.(1..=254).1 里的高位段; + // 这里只挑实测遇到的与常见默认值,避免误伤家用 192.168.0/1.1 + (192, 168) => matches!(o[2], 30 | 31 | 56 | 99 | 100 | 152 | 174 | 226), + // WSL2 / Hyper-V 默认在 172.16-31 段 + (172, 16..=31) => true, + _ => false, + } +} + pub fn local_ipv4_endpoints(port: u16) -> Vec { let mut ips = Vec::::new(); if let Ok(addrs) = if_addrs::get_if_addrs() { @@ -247,6 +266,11 @@ pub fn local_ipv4_endpoints(port: u16) -> Vec { ips.sort_by_key(|ip| { if *ip == Ipv4Addr::new(192, 168, 137, 1) { 0 } else if *ip == Ipv4Addr::new(192, 168, 49, 1) { 1 } + // 虚拟网卡(VMware / Hyper-V / WSL / Docker)的地址手机永远到不了, + // 却会占满二维码里有限的名额,把真正可达的地址挤出去——实测中 + // 192.168.30.1、192.168.31.1、172.21.96.1 就是这样把 AP 网关顶掉的。 + // 不删除,只降权:万一某台机器真用这些网段做局域网,仍能兜底。 + else if is_likely_virtual(*ip) { 4 } else if ip.is_private() { 2 } else { 3 } }); @@ -417,3 +441,31 @@ mod qr_endpoint_tests { } } } + +#[cfg(test)] +mod virtual_adapter_tests { + use super::*; + + /// 实测中这三个虚拟网卡地址把 Direct AP 网关挤出了二维码。 + #[test] + fn known_virtual_ranges_are_recognised() { + for ip in ["192.168.30.1", "192.168.31.1", "172.21.96.1", "172.17.0.1"] { + assert!(is_likely_virtual(ip.parse().unwrap()), "{ip} 应被识别为虚拟网卡"); + } + } + + /// 家用路由器最常见的网关不能被误伤,否则真实局域网地址反被降权。 + #[test] + fn common_home_gateways_are_not_treated_as_virtual() { + for ip in ["192.168.0.1", "192.168.1.1", "192.168.8.1", "10.0.0.1"] { + assert!(!is_likely_virtual(ip.parse().unwrap()), "{ip} 不应被当作虚拟网卡"); + } + } + + /// 只有 .1 结尾才可能是虚拟网关;普通主机地址一律不降权。 + #[test] + fn only_gateway_addresses_are_considered() { + assert!(!is_likely_virtual("192.168.30.55".parse().unwrap())); + assert!(!is_likely_virtual("172.21.96.200".parse().unwrap())); + } +}