You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Android应用无法连接netcat服务器,但adb shell可以?

问题分析与解决方案

核心问题

Android应用运行在独立的沙箱环境中,API 29(Android 10)及以上系统默认禁止应用访问回环地址(localhost/127.0.0.1),而adb shell属于系统级进程,不受该沙箱限制,所以能正常通过nc localhost 3000连接主机的反向端口,但应用代码会超时失败。

解决方案

1. 配置网络安全策略,允许应用访问回环地址

在项目的res/xml目录下创建network_security_config.xml文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">127.0.0.1</domain>
    </domain-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

然后在AndroidManifest.xml的application标签中添加引用:

<application
    ...
    android:networkSecurityConfig="@xml/network_security_config">
    ...
</application>

2. 验证adb反向转发有效性

重新执行转发命令并确认状态:

adb reverse tcp:3000 tcp:3000
# 检查转发是否存在
adb reverse --list

如果输出包含tcp:3000 tcp:3000,说明转发正常;否则重新执行转发命令。

3. 代码优化(非必要,但更规范)

代码中runBlocking { t.start() }是多余的,Thread.start()不需要协程阻塞,直接替换为:

t.start()

原理说明

adb反向端口转发是将设备的3000端口映射到主机的3000端口,但Android应用沙箱默认拦截对回环地址的访问,配置网络安全策略后,应用被授权访问localhost/127.0.0.1,从而通过转发端口连接到主机的netcat服务器。

内容的提问来源于stack exchange,提问作者Mauro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 23:33:09