优化WiFi ADB快速扫描

This commit is contained in:
Your Name committed 2026-06-03 08:50:43 +08:00
1 parent e51d37890a
commit 24b58a8c6d
6 files changed
+155 -141

No files matched your search

+112 -103
View File
@@ -22,15 +22,15 @@ DEFAULT_ADB_PORT = 5555
HI_PORT_MIN = 37000
HI_PORT_MAX = 44000
# 高端口补扫先做一轮均匀采样,命中率够高时可以明显缩短等待。
HI_PORT_SAMPLE_COUNT = 320
HI_PORT_SAMPLE_COUNT = 192
FAST_PROBE_TIMEOUT = 0.12
FAST_CONNECT_TIMEOUT = 1.2
MDNS_DISCOVERY_TIMEOUT = 0.8
DEFAULT_SCAN_TIMEOUT = 0.12
MAX_QUICK_HOSTS = 24
# 默认扫描端口集合:
# - 5555 传统 adb tcpip 端口
# - 37000-44999 Android 11+ "无线调试"会用这个范围里的随机端口
# (来自 ADB pairing 协议;不是每次都同一个,所以扫描需要范围)
# 注意:扫整个 8000 端口区间会慢,所以这里只默认扫 5555。
# 用户可在 GUI/CLI 里把 ports 改成 "5555,37000-40000" 等。
# 默认扫描端口集合:5555 是传统 adb tcpip 端口;Android 11+ 无线调试
# 随机端口走 discover_adb_devices 的 mDNS / ARP / 上次目标快速路径补扫。
DEFAULT_ADB_PORTS: tuple[int, ...] = (DEFAULT_ADB_PORT,)
@@ -344,7 +344,7 @@ def parse_port_spec(spec) -> list[int]:
continue
if not (1 <= lo <= hi <= 65535):
continue
if (hi - lo + 1) > 1024:
if (hi - lo + 1) > 1024 and not (lo == HI_PORT_MIN and hi == HI_PORT_MAX):
continue
for p in range(lo, hi + 1):
if p not in seen:
@@ -427,6 +427,72 @@ def _build_hi_port_candidates(last_port_hint: Optional[int] = None) -> list[int]
return out
def _append_unique_ip(out: list[str], seen: set[str], ip: str, subnet_specs: list[str]) -> None:
try:
ipaddress.IPv4Address(ip)
except Exception:
return
if ip in seen or not _ip_in_subnets(ip, subnet_specs):
return
seen.add(ip)
out.append(ip)
def _build_quick_host_candidates(
subnet_specs: list[str],
*,
last_ip: str = "",
mdns_targets: Optional[list[tuple[str, int]]] = None,
max_hosts: int = MAX_QUICK_HOSTS,
) -> list[str]:
"""Build a small online-likely host list for Android wireless-debug random ports."""
out: list[str] = []
seen: set[str] = set()
if last_ip:
_append_unique_ip(out, seen, last_ip, subnet_specs)
for ip, _port in mdns_targets or []:
_append_unique_ip(out, seen, ip, subnet_specs)
if len(out) >= max_hosts:
return out
arp_added = False
for ip in _list_arp_ipv4_candidates(subnet_specs, max_hosts=max_hosts):
_append_unique_ip(out, seen, ip, subnet_specs)
arp_added = True
if len(out) >= max_hosts:
return out
# If ARP is empty, scan a small prefix of each subnet rather than the whole /24 high range.
if not arp_added:
for spec in subnet_specs:
for ip in parse_subnet_spec(spec):
_append_unique_ip(out, seen, ip, subnet_specs)
if len(out) >= max_hosts:
return out
return out
def _connect_last_target_fast(
adb_exe: str,
target: str,
model: str = "",
) -> Optional[DiscoveredDevice]:
"""Try the remembered target before any broad scanning."""
parsed = _parse_target_ip_port(target)
if not parsed:
return None
ip, port = parsed
state, message = verify_adb_target(adb_exe, f"{ip}:{port}", timeout=FAST_CONNECT_TIMEOUT)
if state not in ("connected", "unauthorized"):
return None
dev = DiscoveredDevice(ip=ip, port=port, adb_state=state, message=message)
if state == "connected":
dev.model = model or query_device_model(adb_exe, dev.target)
return dev
# ============================================================
# TCP 端口探测
# ============================================================
@@ -546,7 +612,7 @@ def discover_mdns_targets(adb_exe: str) -> list[tuple[str, int]]:
"""
if not adb_exe:
return []
rc, out = _run_adb(adb_exe, ["mdns", "services"], timeout=4.0)
rc, out = _run_adb(adb_exe, ["mdns", "services"], timeout=MDNS_DISCOVERY_TIMEOUT)
if rc != 0 or not out:
return []
targets: list[tuple[str, int]] = []
@@ -575,7 +641,7 @@ def discover_mdns_targets(adb_exe: str) -> list[tuple[str, int]]:
return targets
def verify_adb_target(adb_exe: str, target: str) -> tuple[str, str]:
def verify_adb_target(adb_exe: str, target: str, timeout: float = 5.0) -> tuple[str, str]:
"""对一个 ip:port 调 `adb connect <target>`,解析输出。
返回 (state, message):
@@ -583,7 +649,7 @@ def verify_adb_target(adb_exe: str, target: str) -> tuple[str, str]:
- state="unauthorized" adb 协议握手成功但设备未授权
- state="failed" 其他失败
"""
rc, out = _run_adb(adb_exe, ["connect", target], timeout=5.0)
rc, out = _run_adb(adb_exe, ["connect", target], timeout=timeout)
low = out.lower()
if "authenticate" in low or "unauthorized" in low:
return "unauthorized", out
@@ -652,7 +718,7 @@ def discover_adb_devices(
adb_exe: str,
subnet_spec: Optional[str] = None,
port: int = DEFAULT_ADB_PORT,
probe_timeout: float = 0.3,
probe_timeout: float = DEFAULT_SCAN_TIMEOUT,
on_progress: Optional[Callable[[int, int], None]] = None,
on_phase: Optional[Callable[[str], None]] = None,
ports: Optional[Iterable[int]] = None,
@@ -691,6 +757,7 @@ def discover_adb_devices(
else:
subnet_specs = [subnet_spec.strip()]
auto_ports_mode = ports is None or list(ports) == [DEFAULT_ADB_PORT]
port_list = list(ports) if ports else [int(port)]
if not port_list:
port_list = [DEFAULT_ADB_PORT]
@@ -698,8 +765,9 @@ def discover_adb_devices(
# 1.5) 利用上次成功目标加速:优先直连上次 target;并把上次端口作为补充端口。
last_target = ""
last_model = ""
last_ip_hint = ""
last_port_hint: Optional[int] = None
if port_list == [DEFAULT_ADB_PORT]:
if auto_ports_mode:
try:
from . import config as wifi_config
@@ -715,34 +783,16 @@ def discover_adb_devices(
if parsed_last:
last_ip, last_port_hint_val = parsed_last
if _ip_in_subnets(last_ip, subnet_specs):
last_ip_hint = last_ip
last_port_hint = last_port_hint_val
if last_port_hint != DEFAULT_ADB_PORT and last_port_hint not in port_list:
port_list = [DEFAULT_ADB_PORT, last_port_hint]
if on_phase:
try:
on_phase(f"快速验证上次目标 {last_ip}:{last_port_hint}")
except Exception:
pass
if _is_mocked_callable(get_last_wifi_target_fn) and probe_adb_port(
last_ip,
last_port_hint,
timeout=min(max(probe_timeout, 0.01), FAST_PROBE_TIMEOUT),
):
state, message = verify_adb_target(
adb_exe, f"{last_ip}:{last_port_hint}"
)
if state in ("connected", "unauthorized"):
dev = DiscoveredDevice(
ip=last_ip,
port=last_port_hint,
adb_state=state,
message=message,
)
if state == "connected":
dev.model = last_model
if not dev.model:
dev.model = query_device_model(adb_exe, dev.target)
return [dev]
dev = _connect_last_target_fast(adb_exe, f"{last_ip}:{last_port_hint}", last_model)
if dev is not None:
return [dev]
# 2) mDNS 发现(Android 11+ 无线调试常见随机端口)
mdns_targets = discover_mdns_targets(adb_exe)
@@ -752,6 +802,30 @@ def discover_adb_devices(
except Exception:
pass
quick_open_targets: list[tuple[str, int]] = []
if auto_ports_mode:
quick_hosts = _build_quick_host_candidates(
subnet_specs,
last_ip=last_ip_hint,
mdns_targets=mdns_targets,
max_hosts=MAX_QUICK_HOSTS,
)
quick_ports = _build_hi_port_candidates(last_port_hint)
if last_port_hint and last_port_hint not in quick_ports:
quick_ports.insert(0, last_port_hint)
if quick_hosts and quick_ports:
if on_phase:
try:
on_phase(f"快速补扫 {len(quick_hosts)} 台在线候选 × {len(quick_ports)} 个无线调试高端口")
except Exception:
pass
quick_open_targets = scan_open_ports(
quick_hosts,
ports=quick_ports,
timeout=min(max(probe_timeout, 0.01), 0.025),
max_workers=256,
)
# 3) 端口扫描(支持多子网补扫)
all_open_targets: list[tuple[str, int]] = []
total_ips = 0
@@ -770,9 +844,10 @@ def discover_adb_devices(
on_phase(f"扫描 {spec}({len(ips)} 个 IP × {ports_label})")
except Exception:
pass
base_ports = [DEFAULT_ADB_PORT] if auto_ports_mode else port_list
open_targets = scan_open_ports(
ips,
ports=port_list,
ports=base_ports,
timeout=probe_timeout,
on_progress=on_progress,
)
@@ -781,6 +856,7 @@ def discover_adb_devices(
# 合并 mDNS + 网段扫描,并去重
all_targets = list(mdns_targets)
all_targets.extend(quick_open_targets)
all_targets.extend(all_open_targets)
uniq_open: list[tuple[str, int]] = []
seen_open: set[tuple[str, int]] = set()
@@ -790,73 +866,6 @@ def discover_adb_devices(
seen_open.add(t)
uniq_open.append(t)
# 2.5) 随机端口补扫:
# 在无线调试场景中,端口常落在 37000~44000;当 mDNS 为空且 5555 未命中时,
# 对 ARP 里“看起来在线”的少量主机做一次窄范围补扫,提升命中率。
default_or_hint_ports = port_list == [DEFAULT_ADB_PORT]
if (
not default_or_hint_ports
and isinstance(last_port_hint, int)
and last_port_hint != DEFAULT_ADB_PORT
):
default_or_hint_ports = port_list == [DEFAULT_ADB_PORT, last_port_hint]
if (
auto_subnet_mode
and not uniq_open
and not mdns_targets
and default_or_hint_ports
):
arp_ips = _list_arp_ipv4_candidates(subnet_specs, max_hosts=8)
if not arp_ips:
for spec in subnet_specs:
for ip in parse_subnet_spec(spec):
if ip not in arp_ips:
arp_ips.append(ip)
if len(arp_ips) >= 8:
break
if len(arp_ips) >= 8:
break
if arp_ips:
sampled_hi_ports = _build_hi_port_candidates(last_port_hint)
if on_phase:
try:
on_phase(
f"5555 未命中,补扫 ARP 候选主机 {len(arp_ips)} 台的 {len(sampled_hi_ports)} 个高端口候选"
)
except Exception:
pass
hi_open = scan_open_ports(
arp_ips,
ports=sampled_hi_ports,
timeout=min(probe_timeout, 0.05),
max_workers=128,
)
# 候选端口没命中再做全范围兜底,兼顾速度和命中率。
if not hi_open:
if on_phase:
try:
on_phase("高端口候选未命中,执行 37000-44000 全范围兜底补扫(可能较慢)")
except Exception:
pass
full_hi_ports = list(range(HI_PORT_MIN, HI_PORT_MAX + 1))
for arp_ip in arp_ips:
host_open = scan_open_ports(
[arp_ip],
ports=full_hi_ports,
timeout=min(probe_timeout, 0.05),
max_workers=128,
)
if host_open:
hi_open.extend(host_open)
# 一旦命中,先返回这一批,不再继续扫其它主机。
break
for t in hi_open:
if t in seen_open:
continue
seen_open.add(t)
uniq_open.append(t)
if not uniq_open:
return []