【发布时间】:2018-05-28 12:21:31
【问题描述】:
我没有找到正确的解决方案。下面的代码给了我本地 IP 地址(如果我连接到 Wifi,它会给出类似 192.168.0.x 的 IP 地址),但我想要公共 IP 地址(就像我在 google 中搜索“我的 IP 是什么”一样)
public static 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() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
或
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
有人可以帮忙吗?谢谢!
【问题讨论】:
标签: android networking ip