android获取设备eth0,eth1,wlan0的IP地址

   在做一些跟网络相关的需求时,很多时候需要获取到相关网络类型的IP地址,如下图:

       

  这个时候用什么方法来获取这个IP地址呢?楼主在之前的开发中,找到了以下方法,代码如下,仅供参考:


/**
     * Get Ip address 自动获取IP地址
     *
     * @throws SocketException
     */
    public static String getIpAddress(String ipType) throws SocketException {
        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();

                if (ni.getName().equals(ipType)) {


                    Enumeration<InetAddress> ias = ni.getInetAddresses();
                    while (ias.hasMoreElements()) {

                        ia = ias.nextElement();
                        if (ia instanceof Inet6Address) {
                            continue;// skip ipv6
                        }
                        String ip = ia.getHostAddress();

                        // 过滤掉127段的ip地址
                        if (!"127.0.0.1".equals(ip)) {
                            hostIp = ia.getHostAddress();
                            break;
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        Log.d("vivi", "get the IpAddress--> " + hostIp + "");
        return hostIp;
    }
    其中的ipType就是需要获取的网络ip地址类型,我们可以传入eth1,eth0,wlan0,等,为了正确获取到ip地址,我们需要过滤掉ipv6的地址和127.0.0.1。

    感谢阅读,有什么不对的地方还请大家指正。

   


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值