如何通过IPv4网络地址的用Java或Android逐个列表遍历? [英] How to iterate through the list of IPv4 network addresses in Java or Android one by one?

查看:199
本文介绍了如何通过IPv4网络地址的用Java或Android逐个列表遍历?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何由一个经过Java或Android的一个可用的IPv4网络地址的列表迭代?

How to iterate through the list of available IPv4 network addresses in Java or Android one by one?

[这是一个自我回答提问]

推荐答案

一个可能的解决方案是:

A possible solution is the following:

   private Enumeration<NetworkInterface> networkInterfaces = null;
   private Enumeration<InetAddress> networkAddresses = null;

   ...
        try
        {
            while(true)
            {
                if(this.networkInterfaces == null)
                {
                    networkInterfaces = NetworkInterface.getNetworkInterfaces();
                }
                if(networkAddresses == null || !networkAddresses.hasMoreElements())
                {
                    if(networkInterfaces.hasMoreElements())
                    {
                        NetworkInterface networkInterface = networkInterfaces.nextElement();
                        networkAddresses = networkInterface.getInetAddresses();
                    }
                    else
                    {
                        networkInterfaces = null;
                    }
                }
                else
                {
                    if(networkAddresses.hasMoreElements())
                    {
                        String address = networkAddresses.nextElement().getHostAddress();
                        if(address.contains(".")) //IPv4 address
                        {
                            textView.setText(address);
                        }
                        break;
                    }
                    else
                    {
                        networkAddresses = null;
                    }
                }
            }
        }
        catch(SocketException e)
        {
            e.printStackTrace();
        }

在一个按钮的点击,这将显示的IP地址更改为网络接口上的下一个可用的IP地址。这样一来,就可以显示在一个时间的IP地址之一。

On the click of a button, this would change the displayed IP address to the next available IP address on the network interface. This way, it is possible to display the IP addresses one at a time.

这篇关于如何通过IPv4网络地址的用Java或Android逐个列表遍历?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆