關於android4.0 獲取手機IP地址的問題

獲取手機IP地址的代碼:

[java] 
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 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<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() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {   
                             
                            return inetAddress.getHostAddress().toString();   
                        }   
                    }   
             } 
        }catch (SocketException e) { 
            // TODO: handle exception 
            Utils.log("WifiPreference IpAddress—error-" + e.toString()); 
        } 
         
        return null;  
    } 

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *