Short of parsing the output of ipconfig
, does anyone have a 100% pure java way of doing this?
One of the most useful pieces of information you can get from a network interface is the list of IP addresses that are assigned to it. You can obtain this information from a NetworkInterface instance by using one of two methods. The first method, getInetAddresses() , returns an Enumeration of InetAddress .
By default, each network interface card (NIC) has its own unique IP address. However, you can assign multiple IP addresses to a single NIC.
Each of these network interfaces can now have up to 250 IP addresses associated with it, enabling new capabilities listed in the documentation for assigning multiple IP addresses by using PowerShell.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With