android 獲取本機IP地址

private String getLocalIPAddress() throws SocketException{  
    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();  
            }  
        }  
    }  
    return "null";  
}

可是,在android4.0以上系統中,上面的代碼僅可以返回一個ipv6的地址,若是須要獲取ip v4的地址,能夠這麼更改:
java

private String getLocalIPAddress() throws SocketException{  
    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() && <strong>(inetAddress instanceof Inet4Address)</strong>){  
                return inetAddress.getHostAddress().toString();  
            }  
        }  
    }  
    return "null";  
}
相關文章
相關標籤/搜索