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;
}
之后程序在别的手机上运行没问题,可在我的galaxy nexus上则获取到了类似fe80::b607:f9ff:fee5:487e..这样的IP地址。因为最近我的手机升到了4.0.4,所以怀疑是系统原因。
经过一番努力,终于找出原因。
上面的IP地址是IPV6的地址形式(大概这个意思,具体没有太深入研究)。解决方法是,在上面代码中的最内层的for循环的if语句中对inetAddress进行格式判断,只有其是IPV4格式地址时,才返回值。修改后代码如下:
public String getLocalIpAddress() {
try {
String ipv4;
List nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface ni: nilist)
{
List ialist = Collections.list(ni.getInetAddresses());
for (InetAddress address: ialist){
if (!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4=address.getHostAddress()))
{
return ipv4;
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
本人手中也只有这个4.0.4的系统,不知道别的4.0版本的手机是否会出现此问题,不过如果有,解决方法一样。
希望对大家有所帮助。。