Enumerating Network Interfaces and Querying Their IP Addresses

Login | Register

Enumerating Network Interfaces and Querying Their IP Addresses

Network

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
      .getNetworkInterfaces();
    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");
        else
          System.out.println("IP Address: IPv6");
        System.out.println("");
      }
    }
  }
}
$ java ShowInterfaces
Name:eth1
Display Name:eth1
Host Address:192.168.0.112
Host Name:beefy.local
IP Address: IPv4
Name:lo
Display Name:lo
Host Address:0:0:0:0:0:0:0:1%1
Host Name:localhost6.localdomain6
IP Address: IPv6
Name:lo
Display Name:lo
Host Address:127.0.0.1
Host Name:localhost.localdomain
IP Address: IPv4

About

At Develop In Java, we've been a part of the Java community for over 10 years. If there's anything you'd like us to cover, just ask !

Current versions

  • Java - 1.8
  • Java EE - 7
  • Spring - 4.x