Android 4.0.3获取本地IP
我对安卓4.0.3有问题。我正在使用以下方法获取本地IP:Android 4.0.3获取本地IP,android,wifi,Android,Wifi,我对安卓4.0.3有问题。我正在使用以下方法获取本地IP: public static String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement();
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()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
公共静态字符串getLocalIpAddress(){
试一试{
对于(枚举en=NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){
NetworkInterface intf=en.nextElement();
对于(枚举Enumeration EnumipAddress=intf.getInetAddresses();EnumipAddress.hasMoreElements();){
InetAddress InetAddress=enumIpAddr.nextElement();
如果(!inetAddress.isLoopbackAddress()){
返回inetAddress.getHostAddress().toString();
}
}
}
}捕获(SocketException例外){
例如printStackTrace();
}
返回null;
}
它在android v2.1-2.3上运行得非常好。但在android 4.0.3的emulator上,它会返回类似mac地址:fe80::fad0:bdff:fe4d:4871的信息。有人能解释一下发生了什么吗?您最好使用它
正如我提到的,您获得的地址是IPv6地址&您无法将IPv6地址转换为IPv4地址。您最好使用
正如我提到的,您获得的地址是IPv6地址&您无法将IPv6地址转换为IPv4地址。若要仅获取IPv4地址,请更改
if (!inetAddress.isLoopbackAddress()) {
到
要仅获取IPv4地址,请更改
if (!inetAddress.isLoopbackAddress()) {
到
检查是否(!inetAddress.isLoopbackAddress()&&&!isIPV6(inetAddress))如何将其转换为IPv4?我认为您无法转换地址检查是否(!inetAddress.isLoopbackAddress()&&&!isIPV6(inetAddress))如何将其转换为IPv4?我不认为您可以转换地址不兼容的条件操作数类型InetAddress和Inet4Address不兼容的条件操作数类型InetAddress和Inet4Address