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

家住魔仙堡 提交于 2019-12-13 04:06:46

问题


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

[this is a self-answered question]


回答1:


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();
        }

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.



来源:https://stackoverflow.com/questions/25503000/how-to-iterate-through-the-list-of-ipv4-network-addresses-in-java-or-android-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!