fix(wifi-adb): improve scan with multi-subnet fallback and mdns discovery
This commit is contained in:
1 parent
de21921d03
commit
f76232f2fc
6 files changed
+235
-32
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user