我希望能够通过代码获取当前运行的Android模拟器的IP地址。如何实现?
我希望能够通过代码获取当前运行的Android模拟器的IP地址。如何实现?
请澄清:在您的应用程序内,您可以简单地将仿真器称为“localhost
”或127.0.0.1
。
Web流量通过开发机路由,因此仿真器的外部IP是由互联网提供商分配给该开发机的任何外部IP。可以始终从您的设备访问开发机位于10.0.2.2
。
如果启动了多个仿真器,则除非您选择一个通过仿真器的本地IP(例如adb -s 192.168.232.2:5555 shell
),否则不会工作:
10.0.2.1
),而不是直接路由。因此,在这个路由器10.0.2.1
和主机/开发机127.0.0.1/10.0.2.2
之间应该会有一个额外的连接。我通常更改要连接的端口号。 - stdout如果你确实想要将IP分配给你的模拟器:
adb shell
ifconfig eth0
可能会给你类似这样的东西:eth0: ip 10.0.2.15 mask 255.255.255.0 flags [up broadcast running multicast]
或者,如果上述方法失败,请尝试:adb shell
ifconfig wlan0
在输出中查找
inet addr:
,例如,我的模拟器日志中出现了inet addr:192.168.232.2
adb shell
命令后,我遇到了这个错误:ifconfig: eth0: No such device
。你有什么想法是出现这种情况的原因吗? - awavi像这样:
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
查看文档获取更多信息:NetworkInterface。
使用此方法,您将获得Android模拟器的100%正确IP地址。
要获取您的模拟器的IP地址:
进入adb shell并输入此命令。
adb shell
ifconfig eth0
运行该命令后我得到了:
IP : 10.0.2.15
掩码 : 255.255.255.0
这对我很有效。我也在开发一个网络应用程序。
ifconfig: en0: No such device
。 - Dr.jackyhttp://10.0.2.2:3000/api
,例如用于Web API。 - undefinedpublic String getLocalIpAddress() {
try {
for (Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration < InetAddress > enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
在我的应用程序代码中,我可以轻松获取运行设备的IP地址,如下所示:
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());