问题
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