1

Android 获取 IP 地址

 2 years ago
source link: https://www.kymjs.com/note/2018/09/10/01/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Android 获取 IP 地址

2018-09-10 By 张涛 | 本文已被访问3041次

版权声明: 本文是开源实验室原创文章,如您转载必须以链接形式注明原文地址:https://kymjs.com/note/2018/09/10/01
对本知识点有任何问题,可加我的个人微信:kymjs123

开发中经常会需要判断当前是否连接网络, WiFi 或 移动数据连接判断的需求。经常使用的方法是如下两种:

第一种方法

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);  
  WifiInfo wifiInfo = wifiManager.getConnectionInfo();  
  int ipAddress = wifiInfo.getIpAddress();

通过这种方式获取到的 IP 地址为一串数字,我们并不能看懂,因此我们需要通过下面的方法进行转换:

String ip = (ipAddress & 0xff) + "." + (ipAddress>>8 & 0xff) + "." + (ipAddress>>16 & 0xff) + "." + (ipAddress >> 24 & 0xff);  

这样转换之后,我们获取到的 IP 地址就是我们平时认识的, 比如: 192.168.1.108

这种方法在飞行模式下获取到的 IP 地址为 0.0.0.0

第二种方法

public 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 ex) {  
        Log.e(LOG_TAG, ex.toString());  
    }  
    return null;  
}

第二种方式是比较通用的,在WiFi和3G/4G 状态下,都可以获取到正确的地址.但是在高版本 Android 设备上获取到的是 IVP6地址,比如: fe80::8e3a:e3ff:fe45:a018
需要在if (!inetAddress.isLoopbackAddress())中加一条判断,改为if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) 就能成功获取到 IVP4的地址了.

这种方法在手机处于飞行状态下时, 获取到的 IP 地址为 null

了解更多有深度技术的文章,与移动端、大前端未来方向的认知,前往订阅 开源实验室小专栏。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK