Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 關於android4.0 獲取手機IP地址的問題

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

編輯:關於Android編程

獲取手機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;  
    } 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved