关于android4.0 获取手机IP地址的问题
获取手机IP地址的代码:
[java]
public static String getLocalIpAddress(){
try{
for (Enumeration<NetworkInte易做图ce> en = NetworkInte易做图ce.getNetworkInte易做图ces(); en.hasMoreElements();) {
NetworkInte易做图ce intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
}catch (SocketException e) {
// TODO: handle exception
Utils.log("WifiPreference IpAddress---error-" + e.toString());
}
return null;
}
但是在4.0 下 会出现类似fe80::b607:f9ff:fee5:487e的IP地址, 这个是IPV6的地址,我们需要获得是的IPV4的地址,所以要在上诉代码中加一个判断
[java]
InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())
完整代码如下:
[java]
public static String getLocalIpAddress(){
try{
for (Enumeration<NetworkInte易做图ce> en = NetworkInte易做图ce.getNetworkInte易做图ces(); en.hasMoreElements();) {
NetworkInte易做图ce intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
return inetAddress.getHostAddress().toString();
}
}
}
}catch (SocketException e) {
// TODO: handle exception
Utils.log("WifiPreference IpAddress---error-" + e.toString());
}
return null;
}
补充:移动开发 , Android ,