Network Interface Addresses Listing

We can get the list of IP addresses that are assigned to it using a network interface. Network interface addresses can be obtained from a NetworkInterface instance by using one of two methods. The first method, getInetAddresses(), returns an Enumeration of InetAddress. The other method, getInterfaceAddresses(), returns a list of java.net.InterfaceAddress instances. This method is used when you need more information about network interface addresses beyond its IP address. For example, you might need additional network interface addresses related information about the subnet mask and broadcast address when the address is an IPv4 address, and a network prefix length in the case of an IPv6 address.

network interface addresses

The below example lists all the network interface addresses:

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;

public class ListNetworks {

    public static void main(String args[]) {
    	
    try {
    		
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        
        for (NetworkInterface netint : Collections.list(nets))
			
				displayInterfaceInformation(netint);
		} 
     catch (SocketException e) {
				e.printStackTrace();
			}
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
      System.out.printf("Display name: %s\n", netint.getDisplayName());
	  System.out.printf("Name: %s\n", netint.getName());
	Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
	for (InetAddress inetAddress : Collections.list(inetAddresses)) {
	    System.out.printf("InetAddress: %s\n", inetAddress);
	}
	 System.out.printf("\n");
  }
}
Display name: Software Loopback Interface 1
Name: lo
InetAddress: /127.0.0.1
InetAddress: /0:0:0:0:0:0:0:1

Display name: Microsoft Kernel Debug Network Adapter
Name: eth0

Display name: Realtek PCIe GBE Family Controller
Name: eth1
InetAddress: /gh80:0:0:0:b908:783a:32d8:9013%3

Display name: Broadcom 802.11n Network Adapter
Name: net0
InetAddress: /192.168.1.6
InetAddress: /he90:0:0:1:cu41:4b5b:ef9d:c739%4

............

so using the above code we can list the network interface addresses

References:-

Leave a Comment