How To Iterate Through The List Of Ipv4 Network Addresses In Java Or Android One By One?
How to iterate through the list of available IPv4 network addresses in Java or Android one by one? [this is a self-answered question]
Solution 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())
{
NetworkInterfacenetworkInterface= networkInterfaces.nextElement();
networkAddresses = networkInterface.getInetAddresses();
}
else
{
networkInterfaces = null;
}
}
else
{
if(networkAddresses.hasMoreElements())
{
Stringaddress= 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.
Post a Comment for "How To Iterate Through The List Of Ipv4 Network Addresses In Java Or Android One By One?"