How to enumerate IP addresses of all enabled NIC cards from Java? How to enumerate IP addresses of all enabled NIC cards from Java? java java

How to enumerate IP addresses of all enabled NIC cards from Java?


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


This code only works in Java 1.6 because of the added InterfaceAddress code.

  try  {     System.out.println("Output of Network Interrogation:");     System.out.println("********************************\n");     InetAddress theLocalhost = InetAddress.getLocalHost();     System.out.println(" LOCALHOST INFO");     if(theLocalhost != null)     {        System.out.println("          host: " + theLocalhost.getHostName());        System.out.println("         class: " + theLocalhost.getClass().getSimpleName());        System.out.println("            ip: " + theLocalhost.getHostAddress());        System.out.println("         chost: " + theLocalhost.getCanonicalHostName());        System.out.println("      byteaddr: " + toMACAddrString(theLocalhost.getAddress()));        System.out.println("    sitelocal?: " + theLocalhost.isSiteLocalAddress());        System.out.println("");     }     else     {        System.out.println(" localhost was null");     }     Enumeration<NetworkInterface> theIntfList = NetworkInterface.getNetworkInterfaces();     List<InterfaceAddress> theAddrList = null;     NetworkInterface theIntf = null;     InetAddress theAddr = null;     while(theIntfList.hasMoreElements())     {        theIntf = theIntfList.nextElement();        System.out.println("--------------------");        System.out.println(" " + theIntf.getDisplayName());        System.out.println("          name: " + theIntf.getName());        System.out.println("           mac: " + toMACAddrString(theIntf.getHardwareAddress()));        System.out.println("           mtu: " + theIntf.getMTU());        System.out.println("        mcast?: " + theIntf.supportsMulticast());        System.out.println("     loopback?: " + theIntf.isLoopback());        System.out.println("          ptp?: " + theIntf.isPointToPoint());        System.out.println("      virtual?: " + theIntf.isVirtual());        System.out.println("           up?: " + theIntf.isUp());        theAddrList = theIntf.getInterfaceAddresses();        System.out.println("     int addrs: " + theAddrList.size() + " total.");        int addrindex = 0;        for(InterfaceAddress intAddr : theAddrList)        {           addrindex++;           theAddr = intAddr.getAddress();           System.out.println("            " + addrindex + ").");           System.out.println("            host: " + theAddr.getHostName());           System.out.println("           class: " + theAddr.getClass().getSimpleName());           System.out.println("              ip: " + theAddr.getHostAddress() + "/" + intAddr.getNetworkPrefixLength());           System.out.println("           bcast: " + intAddr.getBroadcast().getHostAddress());           int maskInt = Integer.MIN_VALUE >> (intAddr.getNetworkPrefixLength()-1);           System.out.println("            mask: " + toIPAddrString(maskInt));           System.out.println("           chost: " + theAddr.getCanonicalHostName());           System.out.println("        byteaddr: " + toMACAddrString(theAddr.getAddress()));           System.out.println("      sitelocal?: " + theAddr.isSiteLocalAddress());           System.out.println("");        }     }  }  catch (SocketException e)  {     e.printStackTrace();  }  catch (UnknownHostException e)  {     e.printStackTrace();  }

The "toMACAddrString" method looks like this:

public static String toMACAddrString(byte[] a){  if (a == null)  {     return "null";  }  int iMax = a.length - 1;  if (iMax == -1)  {     return "[]";  }  StringBuilder b = new StringBuilder();  b.append('[');  for (int i = 0;; i++)  {     b.append(String.format("%1$02x", a[i]));     if (i == iMax)     {        return b.append(']').toString();     }     b.append(":");  }}

and the "toIPAddrString" method is here:

public static String toIPAddrString(int ipa){   StringBuilder b = new StringBuilder();   b.append(Integer.toString(0x000000ff & (ipa >> 24)));   b.append(".");   b.append(Integer.toString(0x000000ff & (ipa >> 16)));   b.append(".");   b.append(Integer.toString(0x000000ff & (ipa >> 8)));   b.append(".");   b.append(Integer.toString(0x000000ff & (ipa)));   return b.toString();}

I have that first set of code in the try/catch above in a method called dump() in class called IPConfig. Then I just put a main method in IPConfig to call new IPConfig().dump() so that when I'm trying to figure out some wacky network problem, I can see Java thinks is going on. I figured out that my Fedora box reports different information than Windows for the LocalHost information and it was causing my Java programs some issues.

I realize its similiar to the other answers but it prints out nearly everything interesting that you can get from the interface and ipaddress apis.