你好,我用这种方法获取移动网络IP地址
public static String getMobileIPAddress() {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
return addr.getHostAddress();
}
}
}
} catch (Exception ex) { } // for now eat exceptions
return "";
}但是返回值似乎不是IP :fe80::dc19 19:94ff:fe6f:ae7b% but 0
发布于 2020-01-26 10:37:53
实际上你的代码是正确的。它得到了InetAddresses列表,其中ip地址也与mac地址一起出现。您必须使用InetAddressUtils.isIPv4Address或addr instanceof Inet4Address (API >= 23)来过滤其中的ip地址。检查如下:
public static String getMobileIPAddress() {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress() &&
addr instanceof Inet4Address) {
return addr.getHostAddress();
}
}
}
} catch (Exception ex) { } // for now eat exceptions
return "";
}发布于 2020-01-26 10:46:50
此代码获取WIFI IP地址:
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());https://stackoverflow.com/questions/59917307
复制相似问题