Enumerating Network Interfaces and Querying Their IP Addresses

In Java, we can enumerate network interfaces using the NetworkInterface.getNetworkInterfaces() method. This returns an enumeration of NetworkInterface objects.

Each NetworkInterface object can be enumerated over using the getInetAddresses() method to obtain all the InetAddresses that are associated with the NetworkInterface.

An InetAddress object is actually instantiated as an Inet4Address or Inet6Address in this instance and can be used to indicate whether an interface supports IPv4 or IPv6.

The following code shows how to enumerate over the local network cards and print out the interface name/display name, the host address/name and whether the IP address supports IPv4 or IPv6.

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class ShowInterfaces {
  public static void main(String args[]) throws SocketException {
    Enumeration<NetworkInterface> interfaces = NetworkInterface
    while (interfaces.hasMoreElements()) {
      NetworkInterface ni = (NetworkInterface) interfaces.nextElement();
      Enumeration<InetAddress> addresses = ni.getInetAddresses();
      while (addresses.hasMoreElements()) {
        InetAddress inetAddress = (InetAddress) addresses.nextElement();
        System.out.println("Name:" + ni.getName());
        System.out.println("Display Name:" + ni.getDisplayName());
        System.out.println("Host Address:"
          + inetAddress.getHostAddress());
        System.out.println("Host Name:" + inetAddress.getHostName());
        if (inetAddress instanceof Inet4Address)
          System.out.println("IP Address: IPv4");
          System.out.println("IP Address: IPv6");
$ java ShowInterfaces
Display Name:eth1
Host Address:
Host Name:beefy.local
IP Address: IPv4
Display Name:lo
Host Address:0:0:0:0:0:0:0:1%1
Host Name:localhost6.localdomain6
IP Address: IPv6
Display Name:lo
Host Address:
Host Name:localhost.localdomain
IP Address: IPv4