How to enumerate IP addresses of all enabled NIC cards from Java?
Short of parsing the output of ipconfig
, does anyone have a 100% pure java way of doing this?
This is pretty easy:
try {
InetAddress localhost = InetAddress.getLocalHost();
LOG.info(" IP Addr: " + localhost.getHostAddress());
// Just in case this host has multiple IP addresses....
InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
if (allMyIps != null && allMyIps.length > 1) {
LOG.info(" Full list of IP addresses:");
for (int i = 0; i < allMyIps.length; i++) {
LOG.info(" " + allMyIps[i]);
}
}
} catch (UnknownHostException e) {
LOG.info(" (error retrieving server host name)");
}
try {
LOG.info("Full list of Network Interfaces:");
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
LOG.info(" " + intf.getName() + " " + intf.getDisplayName());
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
LOG.info(" " + enumIpAddr.nextElement().toString());
}
}
} catch (SocketException e) {
LOG.info(" (error retrieving network interface list)");
}
Some of this will only work in JDK 1.6 and above (one of the methods was added in that release.)
List<InetAddress> addrList = new ArrayList<InetAddress>();
for(Enumeration<NetworkInterface> eni = NetworkInterface.getNetworkInterfaces(); eni.hasMoreElements(); ) {
final NetworkInterface ifc = eni.nextElement();
if(ifc.isUp()) {
for(Enumeration<InetAddress> ena = ifc.getInetAddresses(); ena.hasMoreElements(); ) {
addrList.add(ena.nextElement());
}
}
}
Prior to 1.6, it's a bit more difficult - isUp() isn't supported until then.
FWIW: The Javadocs note that this is the correct approach for getting all of the IP addresses for a node:
NOTE: can use getNetworkInterfaces()+getInetAddresses() to obtain all IP addresses for this node