Android获取IPV4的方法

来源:互联网 发布:智慧足迹大数据 编辑:程序博客网 时间:2024/05/18 00:07
我是最近才接触Android的Android小白,领导给了一个任务让我去写一个获取手机IP地址的功能,这些东西网上应该有很多类似的,貌似很简单。于是上网搜了很多。开始找到的是这种方法
  public String getLocalHostIp()    {        String ipaddress = "";        try        {            Enumeration<NetworkInterface> en = NetworkInterface                    .getNetworkInterfaces();            // 遍历所用的网络接口            while (en.hasMoreElements())            {                NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip                Enumeration<InetAddress> inet = nif.getInetAddresses();                // 遍历每一个接口绑定的所有ip                while (inet.hasMoreElements())                {                    InetAddress ip = inet.nextElement();                    if (!ip.isLoopbackAddress()                            && InetAddressUtils.isIPv4Address(ip                                    .getHostAddress()))                    {                        return ipaddress = "本机的ip是" + ":" + ip.getHostAddress();                    }                }            }        }        catch (SocketException e)        {            Log.e("feige", "获取本地ip地址失败");            e.printStackTrace();        }        return ipaddress;    }
然后我就自己用Android Studio自己创建了一个项目,来试试能不能获取手机的IP地址(因为网上很多,我就不写要添加的权限),代码复制到了Android Studio上去,发现InetAddressUtils 这个飘红,上网搜了一下发现要用这个东西需要引入commons-lang.jar这个第三方包。我不是太想引入第三方包,就考虑用其他的方法解决,在打InetAddress的时候发现AS提示了Inet4Address 这个类,上去搜了一下Inet4Adress的用法 发现用Inet4Adress可以判断是否是IPV4的地址。我就把代码改成了下面的样子
 public String GetIp() {            try {                for (Enumeration<NetworkInterface> en = NetworkInterface                        .getNetworkInterfaces(); en.hasMoreElements();) {                    NetworkInterface intf = en.nextElement();                    for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr                            .hasMoreElements();) {                        InetAddress inetAddress = ipAddr.nextElement();                        // ipv4地址                        if (!inetAddress.isLoopbackAddress()                                && inetAddress instanceof Inet4Address) {                            return inetAddress.getHostAddress();                        }                    }                }            } catch (Exception ex) {            }            return null;    }

发现代码没有飘红,测试一下,能够获取wifi情况下的IPV4和4G的IPV4,如果没有数据流量关了,也能够返回一个空值。
0 0
原创粉丝点击