Listing all network interfaces in Java

Mostly used for server programs, sometime you need to list all the available network interfaces.

To do this, we will use the InetAddress Java class.

Here is the code that will get all interfaces into a String array:

public static String[] getCurrentAddresses()
{
String [] ret_val=null;
InetAddress [] addrs=null;
try
{
addrs=InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
}
catch (UnknownHostException ex)
{
Logger.getLogger(SingleServer.class.getName()).log(Level.SEVERE, null, ex);
}
if(null!=addrs)
{
int i=0;
ret_val=new String[addrs.length+1];
ret_val[i++]="127.0.0.1";
for(;i<addrs.length;i++)
{
ret_val[i]=addrs[i-1].getHostAddress();
}
}
return ret_val;
}

Now, the thing to note here, is that we must add the 127.0.0.1 (AKA localhost) to this list manually, assuming this is needed. localhost can only be used for local testing, and there for adding it is up to you.