Android 获取移动网络ip地址
您好,我正在使用此方法获取移动网络IP地址Android 获取移动网络ip地址,android,Android,您好,我正在使用此方法获取移动网络IP地址 public static String getMobileIPAddress() { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { Li
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 "";
}
公共静态字符串getMobileIPAddress(){
试一试{
List interfaces=Collections.List(NetworkInterface.getNetworkInterfaces());
用于(网络接口intf:接口){
List addrs=Collections.List(intf.getInetAddresses());
用于(InetAddress地址:地址){
如果(!addr.isLoopbackAddress()){
返回地址getHostAddress();
}
}
}
}catch(Exception-ex){}//现在吃异常
返回“”;
}
但是返回值似乎不是IP:fe80::dc19:94ff:fe6f:ae7b%dummy0实际上您的代码是正确的。它正在获取
inetaddress
的列表,其中ip地址也与mac地址一起出现。您必须使用InetAddressUtils.isIPv4Address
或Inet4Address的addr instanceof
(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 "";
}
公共静态字符串getMobileIPAddress(){
试一试{
List interfaces=Collections.List(NetworkInterface.getNetworkInterfaces());
用于(网络接口intf:接口){
List addrs=Collections.List(intf.getInetAddresses());
用于(InetAddress地址:地址){
如果(!addr.isLoopbackAddress()&&
地址实例(Inet4Address){
返回地址getHostAddress();
}
}
}
}catch(Exception-ex){}//现在吃异常
返回“”;
}
此代码获取WIFI IP地址:
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
你能在这里分享InetAddressUtils图书馆的名字吗!对于API>=23,请参阅下面的内容抱歉,我忘记了它不推荐使用
addr instanceof Inet4Address
。查看我的更新答案此返回wifi ip地址我正在查找移动网络地址