Android 模擬器內部將 **10.0.2.2** 映射到 **宿主機 (開發電腦) 的 127.0.0.1 (localhost)**。因此,模擬器中訪問本機服務器只需將 URL 中的 localhost 或 127.0.0.1 替換為 10.0.2.2。
| 服務器 | 默認端口 | 模擬器訪問 URL |
|---|---|---|
| Tomcat | 8080 | https://10.0.2.2:8080/your-app/api |
| IIS / IIS Express | 80 / 443 / 隨機 | https://10.0.2.2: |
| Node.js / Spring Boot / Python Flask | 3000 / 8080 / 5000 | https://10.0.2.2: |
| Docker 容器 (宿主機網絡模式) | 同上 | https://10.0.2.2: |
**必須綁定 0.0.0.0 (所有介面),而非 127.0.0.1**,否則模擬器無法連接。
# Tomcat server.xml
<Connector port="8080" protocol="HTTP/1.1"
address="0.0.0.0"
connectionTimeout="20000" redirectPort="8443" />
# Spring Boot application.yml
server:
address: 0.0.0.0
port: 8080
# Node.js Express
app.listen(3000, '0.0.0.0', () => console.log('Server running'));
# Python Flask
app.run(host='0.0.0.0', port=5000)
# IIS: 默認綁定所有 IP,無需額外配置
# IIS Express: 修改 .vs/config/applicationhost.config
# (而非 127.0.0.1)
# 需以管理員運行 VS 或預留 URL: netsh http add urlacl url=https://*:port/ user=Everyone
HTTP 服務需在 AndroidManifest.xml <application> 添加:
android:usesCleartextTraffic="true"
或配置 res/xml/network_security_config.xml:
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">10.0.2.2</domain>
<domain includeSubdomains="true">192.168.x.x</domain> <!-- 局域網真機調試 -->
</domain-config>
</network-security-config>
Manifest 應用:android:networkSecurityConfig="@xml/network_security_config"
192.168.1.100) + 端口adb reverse tcp:8080 tcp:8080 → 手機訪問 https://localhost:8080adb pair ip:port + adb connect ip:port模擬器內部 IP: 10.0.2.15 (dhcp 分配) 網關/DNS: 10.0.2.2 ← 映射到宿主機 localhost DNS 服務器: 10.0.2.3 模擬器間通信: 10.0.2.4, 10.0.2.5 ... 宿主機回環: 127.0.0.1 (模擬器自身,非宿主機)
# 模擬器終端 (adb shell) ping 10.0.2.2 curl -v https://10.0.2.2:8080/health # 宿主機終端 netstat -an | findstr :8080 # 確認服務監聽 0.0.0.0:8080
Android 模擬器訪問宿主機服務的「金鑰」是 **10.0.2.2**。配合服務器綁定 0.0.0.0、防火牆放行、Android 9+ 明文流量配置、USB reverse 真機調試,可構建順暢的本地全鏈路開發調試環境。牢記此 IP,告別「localhost 連不上」的困擾。