Android獲取本地IP地址 .

jopen 10年前發布 | 26K 次閱讀 Android Android開發 移動開發

首先說明,這個是察看WIFI的IP地址的方法,還需要添加User Permission(android.permission.ACCESS_WIFI_STATE):

    private String getlocalip(){  
            WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);    
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();    
            int ipAddress = wifiInfo.getIpAddress();   
            Log.d(Tag, "int ip "+ipAddress);  
            if(ipAddress==0)return null;  
            return ((ipAddress & 0xff)+"."+(ipAddress>>8 & 0xff)+"."  
                    +(ipAddress>>16 & 0xff)+"."+(ipAddress>>24 & 0xff));  
        }  

以下是詳細解釋這個方法:

在這里,我們可以是察看WifiInfo中的信息即WifiInfo.getIpAddress(),將返回一個int型的IP地址,我們可以看看源代碼:

    public int getIpAddress() {  
            if (mIpAddress == null || mIpAddress instanceof Inet6Address) return 0;  
           return NetworkUtils.inetAddressToInt(mIpAddress);  
        }  


而NetworkUtils.inetAddressToInt(mIpAddress)是
    public static int inetAddressToInt(InetAddress inetAddr)  
             throws IllegalArgumentException {  
        byte [] addr = inetAddr.getAddress();  
        if (addr.length != 4) {  
        throw new IllegalArgumentException("Not an IPv4 address");}  
        return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |  
              ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);  

所以,獲取到了這個int型的IP地址,我們就還得做一次轉換:
return ((ipAddress & 0xff)+"."+(ipAddress>>8 & 0xff)+"."  
                +(ipAddress>>16 & 0xff)+"."+(ipAddress>>24 & 0xff));  
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!