我想通过代码获取当前运行的Android Emulator的IP地址。 怎么才能实现呢?
澄清一下:在您的应用程序中,您可以简单地将模拟器称为“
localhost
”或127.0.0.1
。
Web 流量通过您的开发计算机进行路由,因此模拟器的 External-IP 是您的互联网提供商分配给该开发计算机的任何外部 IP。您始终可以通过您的设备访问开发机器:
10.0.2.2
。
如果您启动了多个模拟器,其中
adb
不起作用,
除非您通过模拟器的本地 IP 选择一个(如 adb -s 192.168.232.2:5555 shell
),那么:
如果您确实希望将 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
像这样:
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;
}
查看文档以获取更多信息:网络接口。
使用此方法,您将获得 Android 模拟器 100% 正确的 IP 地址
获取模拟器的IP地址
转到 adb shell 并输入此命令
adb shell
ifconfig eth0
运行此命令后,我得到
IP:10.0.2.15
掩码:255.255.255.0
这对我有用。我也在为网络应用程序工作。
如果您需要引用主机的本地主机,例如当您希望模拟器客户端联系主机上运行的服务器时,请使用别名10.0.2.2来引用主机的环回接口。从模拟器的角度来看,localhost (127.0.0.1)指的是它自己的环回接口。
更多详细信息:https://developer.android.com/studio/run/emulator-networking#networkaddresses
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;
}
在我的应用程序的代码中,我可以轻松获取正在运行的设备 IP 地址,如下所示:
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
通常 Android 模拟器的 IP 地址是
10.0.0.2
您可以从模拟器中的 Wi-Fi 设置中查看它