【发布时间】:2015-10-15 22:09:00
【问题描述】:
当我连接到移动网络时,我尝试在 Android 上获取外部 IP 地址值。
我使用以下代码:
public static String ipAddress() {
String ipAddress = "N/A";
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()) {
ipAddress = inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
}
return ipAddress;
}
它返回一个值。可以肯定的是,我还在我的应用程序中使用了类似的服务:http://ifconfig.me/ip.json,它返回外部 IP 地址。
我的问题是服务返回给我的值与方法 ipAddress() 不同。
那么,你能帮我理解一下 ipAddress() 方法有什么问题吗?从 ipAddress() 得到的值是什么意思?
感谢您的帮助。
西尔万
【问题讨论】:
-
你得到了什么值?我打赌你在本地获得 localhost 地址,但网络服务会为你提供网络提供商提供给你手机的地址。
-
ipAddress() 方法返回类似 10.205.250.163 的值。本地主机地址会更喜欢 192.168.xx.xx 不?
-
Localhost 几乎总是 127.0.0.1,但可以是 127.x.x.x 形式的任何内容。
标签: android mobile network-programming ip