Android获取本地IP地址 .

jopen 6年前

首先说明,这个是察看WIFI的IP地址的方法,还需要添加User Permission(android.permission.ACCESS_WIFI_STATE):

</div> </div>
    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));  
</div> </div> </div>