【发布时间】:2010-12-15 18:36:12
【问题描述】:
我想通过代码获取当前运行的Android Emulator的IP地址。 如何实现?
【问题讨论】:
我想通过代码获取当前运行的Android Emulator的IP地址。 如何实现?
【问题讨论】:
澄清一下:在您的应用程序中,您可以简单地将模拟器称为“localhost”或 127.0.0.1。
Web 流量通过您的开发机器进行路由,因此模拟器的外部 IP 是您的提供商分配给该机器的任何 IP。开发机器始终可以从您的设备访问 10.0.2.2。
由于您只询问模拟器的 IP,您想做什么?
【讨论】:
10.0.2.1,而不是直接路由。因此,此路由器之间应该有一个额外的连接@ 987654324@ 到主机/开发机器127.0.0.1/10.0.2.2。我通常会更改我想连接的端口号。
如果您确实希望将 IP 分配给您的模拟器:
adb shell
ifconfig eth0
这会给你类似的东西:
eth0: ip 10.0.2.15 mask 255.255.255.0 flags [up broadcast running multicast]
【讨论】:
adb shell 后出现此错误:ifconfig: eth0: No such deviceany 想法为什么?
wlan0
像这样:
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。
【讨论】:
使用此方法,您将获得 100% 正确的 android 模拟器 IP 地址
获取你的模拟器的ip地址
转到 adb shell 并输入此命令
adb shell
ifconfig eth0
运行此命令后,我得到了
IP:10.0.2.15
掩码:255.255.255.0
这对我有用。我也在为一个网络应用程序工作。
【讨论】:
如果您需要引用主机的 localhost,例如当您希望模拟器客户端联系运行在同一主机上的服务器时,请使用别名 10.0.2.2 来引用主机计算机的环回接口。从模拟器的角度来看,localhost(127.0.0.1)指的是自己的loopback接口。更多详情:http://developer.android.com/guide/faq/commontasks.html#localhostalias
【讨论】:
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());
【讨论】: