fix(wifi-adb): improve scan with multi-subnet fallback and mdns discovery

This commit is contained in:
Your Name committed 2026-06-01 09:40:44 +08:00
1 parent de21921d03
commit f76232f2fc
6 files changed
+235 -32

No files matched your search

+2
View File
@@ -29,6 +29,7 @@ from .wifi_adb_scan import (
DiscoveredDevice,
discover_adb_devices,
get_local_subnet,
get_local_subnets,
parse_port_spec,
parse_subnet_spec,
pick_best_match,
@@ -57,6 +58,7 @@ __all__ = [
"DiscoveredDevice",
"discover_adb_devices",
"get_local_subnet",
"get_local_subnets",
"parse_port_spec",
"parse_subnet_spec",
"pick_best_match",
+153 -28
View File
@@ -13,7 +13,7 @@ import re
import socket
import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from dataclasses import dataclass
from typing import Callable, Iterable, Optional
@@ -115,6 +115,59 @@ def _get_first_private_ipv4() -> Optional[str]:
return None
def _list_private_ipv4s() -> list[str]:
"""枚举本机私有 IPv4(去重,排除回环/link-local)。"""
seen: set[str] = set()
out: list[str] = []
try:
host = socket.gethostname()
infos = socket.getaddrinfo(host, None, family=socket.AF_INET)
except Exception:
infos = []
for info in infos:
ip = info[4][0]
if not ip:
continue
if ip.startswith("127.") or ip.startswith("169.254."):
continue
try:
addr = ipaddress.IPv4Address(ip)
if not addr.is_private:
continue
except Exception:
continue
if ip in seen:
continue
seen.add(ip)
out.append(ip)
# 把出口 IP 提到最前,优先扫当前路由网段
try:
out_ip = _get_outbound_ip()
if out_ip and out_ip in out:
out.remove(out_ip)
out.insert(0, out_ip)
except Exception:
pass
return out
def get_local_subnets() -> list[str]:
"""返回本机可能相关的 /24 私有网段列表(去重,出口网段优先)。"""
ips = _list_private_ipv4s()
nets: list[str] = []
seen: set[str] = set()
for ip in ips:
try:
net = str(ipaddress.IPv4Network(f"{ip}/24", strict=False))
except Exception:
continue
if net in seen:
continue
seen.add(net)
nets.append(net)
return nets
def parse_subnet_spec(spec: str) -> list[str]:
"""把用户输入解析成 IP 列表。支持的格式:
@@ -351,6 +404,44 @@ def _run_adb(adb_exe: str, args: list[str], timeout: float = 5.0) -> tuple[int,
return proc.returncode, out
def discover_mdns_targets(adb_exe: str) -> list[tuple[str, int]]:
"""从 `adb mdns services` 输出中提取可连接的 IPv4:port 目标。
- 支持 _adb._tcp / _adb-tls-connect._tcp 等服务类型;
- 仅提取 IPv4:port(ADB 当前输出本身也是这个格式);
- 结果去重并排序。
"""
if not adb_exe:
return []
rc, out = _run_adb(adb_exe, ["mdns", "services"], timeout=4.0)
if rc != 0 or not out:
return []
targets: list[tuple[str, int]] = []
seen: set[tuple[str, int]] = set()
for line in out.splitlines():
m = re.search(r"(\d{1,3}(?:\.\d{1,3}){3}):(\d{1,5})", line)
if not m:
continue
ip = m.group(1).strip()
try:
port = int(m.group(2))
if not (1 <= port <= 65535):
continue
ipaddress.IPv4Address(ip)
except Exception:
continue
key = (ip, port)
if key in seen:
continue
seen.add(key)
targets.append(key)
try:
targets.sort(key=lambda t: (tuple(int(p) for p in t[0].split(".")), t[1]))
except Exception:
pass
return targets
def verify_adb_target(adb_exe: str, target: str) -> tuple[str, str]:
"""对一个 ip:port 调 `adb connect <target>`,解析输出。
@@ -406,56 +497,84 @@ def discover_adb_devices(
list[DiscoveredDevice],按 IP 排序。state 为 connected / unauthorized / failed。
UI 通常只展示 state != "failed" 的项。
"""
# 1) 推导 IP 列表
# 1) 推导扫描子网列表
subnet_specs: list[str] = []
if subnet_spec is None or not subnet_spec.strip():
subnet = get_local_subnet()
if not subnet:
subnet_specs = get_local_subnets()
# 兼容旧逻辑的兜底
if not subnet_specs:
subnet = get_local_subnet()
if subnet:
subnet_specs = [subnet]
if not subnet_specs:
return []
subnet_spec = subnet
ips = parse_subnet_spec(subnet_spec)
if not ips:
return []
else:
subnet_specs = [subnet_spec.strip()]
port_list = list(ports) if ports else [int(port)]
if not port_list:
port_list = [DEFAULT_ADB_PORT]
if on_phase:
# 2) mDNS 发现(Android 11+ 无线调试常见随机端口)
mdns_targets = discover_mdns_targets(adb_exe)
if on_phase and mdns_targets:
try:
ports_label = (
f"端口 {port_list[0]}"
if len(port_list) == 1
else f"{len(port_list)} 个端口"
)
on_phase(
f"扫描 {subnet_spec}({len(ips)} 个 IP × {ports_label})"
)
on_phase(f"mDNS 发现 {len(mdns_targets)} 个 ADB 候选目标")
except Exception:
pass
# 2) 端口扫描,过滤掉所有指定端口都关闭的 IP
open_targets = scan_open_ports(
ips,
ports=port_list,
timeout=probe_timeout,
on_progress=on_progress,
)
# 3) 端口扫描(支持多子网补扫)
all_open_targets: list[tuple[str, int]] = []
total_ips = 0
for spec in subnet_specs:
ips = parse_subnet_spec(spec)
if not ips:
continue
total_ips += len(ips)
if on_phase:
try:
ports_label = (
f"端口 {port_list[0]}"
if len(port_list) == 1
else f"{len(port_list)} 个端口"
)
on_phase(f"扫描 {spec}({len(ips)} 个 IP × {ports_label})")
except Exception:
pass
open_targets = scan_open_ports(
ips,
ports=port_list,
timeout=probe_timeout,
on_progress=on_progress,
)
if open_targets:
all_open_targets.extend(open_targets)
if not open_targets:
# 合并 mDNS + 网段扫描,并去重
all_targets = list(mdns_targets)
all_targets.extend(all_open_targets)
uniq_open: list[tuple[str, int]] = []
seen_open: set[tuple[str, int]] = set()
for t in all_targets:
if t in seen_open:
continue
seen_open.add(t)
uniq_open.append(t)
if not uniq_open:
return []
if on_phase:
try:
on_phase(
f"发现 {len(open_targets)} 个开放端口的 (IP,端口),验证 ADB"
f"扫描 {len(subnet_specs)} 个网段(共 {total_ips} 个 IP)后,发现 {len(uniq_open)} 个开放端口目标,验证 ADB"
)
except Exception:
pass
# 3) 对每个开放 (IP,Port) 调 adb connect 验证
results: list[DiscoveredDevice] = []
for ip, p in open_targets:
for ip, p in uniq_open:
target = f"{ip}:{p}"
state, message = verify_adb_target(adb_exe, target)
dev = DiscoveredDevice(ip=ip, port=p, adb_state=state, message=message)
@@ -463,6 +582,12 @@ def discover_adb_devices(
dev.model = query_device_model(adb_exe, target)
results.append(dev)
# 稳定排序:IP 数值序 + 端口序
try:
results.sort(key=lambda d: (tuple(int(x) for x in d.ip.split(".")), d.port))
except Exception:
pass
return results
+3 -1
View File
@@ -566,11 +566,12 @@ def handle_post(handler, u, runner, csrf_token: str) -> None:
except Exception:
return handler._send_json({"ok": False, "error": "invalid ports"}, status=400)
try:
from gui.gui_core_pkg import discover_adb_devices, get_local_subnet
from gui.gui_core_pkg import discover_adb_devices, get_local_subnet, get_local_subnets
devs = discover_adb_devices(
adb, subnet_spec=subnet, ports=port_list, probe_timeout=probe_timeout
)
tried_subnets = [subnet] if subnet else (get_local_subnets() or [])
payload = [
{
"target": d.target,
@@ -586,6 +587,7 @@ def handle_post(handler, u, runner, csrf_token: str) -> None:
{
"ok": True,
"subnet": subnet or get_local_subnet() or "",
"subnets": tried_subnets,
"ports": port_list,
"devices": payload,
}
+18
View File
@@ -135,3 +135,21 @@ def test_wifi_auto_reconnect_without_adb_returns_422(monkeypatch):
assert status == 422
assert obj.get("error") == "adb not found"
def test_wifi_scan_includes_tried_subnets(monkeypatch):
monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb")
monkeypatch.setattr(routes, "list_adb_devices", lambda adb: []) # noqa: ARG001
monkeypatch.setattr(routes, "read_config", lambda: {})
monkeypatch.setattr(routes, "write_config", lambda cfg: None) # noqa: ARG001
import gui.gui_core_pkg as core_pkg
monkeypatch.setattr(core_pkg, "parse_port_spec", lambda spec: [5555]) # noqa: ARG001
monkeypatch.setattr(core_pkg, "discover_adb_devices", lambda *a, **k: [])
monkeypatch.setattr(core_pkg, "get_local_subnet", lambda: "192.168.10.0/24")
monkeypatch.setattr(core_pkg, "get_local_subnets", lambda: ["192.168.10.0/24", "10.0.0.0/24"])
status, obj = _post("/api/wifi/scan", {}, monkeypatch)
assert status == 200
assert obj.get("ok") is True
assert obj.get("subnets") == ["192.168.10.0/24", "10.0.0.0/24"]
+54
View File
@@ -79,6 +79,13 @@ class TestGetLocalSubnet:
assert scan.get_local_subnet() is None
class TestGetLocalSubnets:
def test_dedup_and_outbound_first(self):
with patch.object(scan, "_list_private_ipv4s", return_value=["192.168.10.108", "10.0.0.23", "192.168.10.20"]):
subnets = scan.get_local_subnets()
assert subnets == ["192.168.10.0/24", "10.0.0.0/24"]
# ============================================================
# probe_adb_port
# ============================================================
@@ -252,6 +259,23 @@ class TestVerifyAdbTarget:
assert state == "failed"
class TestDiscoverMdnsTargets:
def test_parse_ipv4_targets(self):
sample = """
List of discovered mdns services
adb-1234 _adb-tls-connect._tcp. 192.168.10.66:40075
adb-5678 _adb._tcp. 10.0.0.9:5555
garbage line
"""
with patch.object(scan, "_run_adb", return_value=(0, sample)):
targets = scan.discover_mdns_targets("/adb")
assert targets == [("10.0.0.9", 5555), ("192.168.10.66", 40075)]
def test_empty_on_error(self):
with patch.object(scan, "_run_adb", return_value=(1, "failed")):
assert scan.discover_mdns_targets("/adb") == []
# ============================================================
# discover_adb_devices —— 主入口集成测试
# ============================================================
@@ -332,6 +356,36 @@ class TestDiscoverAdbDevices:
assert captured["ports"] == [5555, 37001]
def test_auto_multi_subnet_fallback_scans_all(self):
calls = []
def fake_scan_ports(ips, **kwargs):
calls.append(list(ips))
# 第一网段无设备,第二网段有一个
if "192.168.10.2" in ips:
return []
return [("10.0.0.9", 5555)]
with patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/30", "10.0.0.8/30"]), \
patch.object(scan, "scan_open_ports", side_effect=fake_scan_ports), \
patch.object(scan, "verify_adb_target", return_value=("connected", "ok")), \
patch.object(scan, "query_device_model", return_value="PEPM00"):
devs = scan.discover_adb_devices("/adb")
assert len(calls) == 2
assert len(devs) == 1
assert devs[0].target == "10.0.0.9:5555"
def test_merges_mdns_targets_before_port_scan(self):
with patch.object(scan, "discover_mdns_targets", return_value=[("192.168.10.66", 40075)]), \
patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/30"]), \
patch.object(scan, "scan_open_ports", return_value=[]), \
patch.object(scan, "verify_adb_target", side_effect=lambda adb, t: ("connected", f"ok:{t}")), \
patch.object(scan, "query_device_model", return_value="PEPM00"):
devs = scan.discover_adb_devices("/adb")
assert len(devs) == 1
assert devs[0].target == "192.168.10.66:40075"
def test_returns_devs_with_correct_ports(self):
"""两个 (ip, port) 分别返回各自端口的 DiscoveredDevice。"""
with patch.object(
+5 -3
View File
@@ -161,13 +161,15 @@ async function wifiScan() {
}
const devs = Array.isArray(resp.devices) ? resp.devices : [];
const subnet = resp.subnet || "";
const subnets = Array.isArray(resp.subnets) ? resp.subnets.filter(Boolean) : [];
const subnetLabel = subnets.length > 0 ? subnets.join(", ") : subnet;
if (!devs.length) {
appendLog([`[WiFi ADB] 扫描完成 (${subnet}),未发现开放 5555 端口的设备`]);
if (status) status.textContent = `扫描完成 (${subnet}),未发现设备`;
appendLog([`[WiFi ADB] 扫描完成 (${subnetLabel}),未发现开放端口设备`]);
if (status) status.textContent = `扫描完成 (${subnetLabel}),未发现设备`;
return;
}
appendLog([
`[WiFi ADB] 扫描完成 (${subnet}),发现 ${devs.length} 台候选: ` +
`[WiFi ADB] 扫描完成 (${subnetLabel}),发现 ${devs.length} 台候选: ` +
devs.map((d) => `${d.target}(${d.state})`).join(", "),
]);