Open In App

How to Retrieve Information about a Network Interface in Java?

In Java, a network interface is known as NIC (Network Interface Card). It is a hardware component, or we can say a software interface which enables a system to connect with a computer network.

Program to Retrieve Information about a Network Interface in Java

Below is the code implementation to retrieve information about a network interface.






// Java program to retrieve information
// About a network interface
import static java.lang.System.out;
  
import java.io.*;
import java.net.*;
import java.net.NetworkInterface;
import java.util.*;
  
// Driver Class
public class GFG {
    // Main Function
    public static void main(String args[])
        throws SocketException
    {
        // collecting network interfaces
        Enumeration<NetworkInterface> nets
            = NetworkInterface.getNetworkInterfaces();
  
        // Iterating the list of Network Interfaces
        for (NetworkInterface netInf :
             Collections.list(nets)) {
            out.printf("Display name: %s\n",
                       netInf.getDisplayName());
            out.printf("Name: %s\n", netInf.getName());
  
            // Displaying Sub Interfaces
            displaySubInterfaces(netInf);
            out.printf("\n");
        }
    }
  
    static void displaySubInterfaces(NetworkInterface netIf)
        throws SocketException
    {
        // Collecting sub networks
        Enumeration<NetworkInterface> subIfs
            = netIf.getSubInterfaces();
  
        // Iterating over sub networks list
        for (NetworkInterface subIf : Collections.list(subIfs)) {
            out.printf("\tSub Interface Display name: %s\n",
                       subIf.getDisplayName());
              
              out.printf("\tSub Interface Name: %s\n",
                       subIf.getName());
        }
    }
}

Output
Display name: eth0
Name: eth0

Display name: lo
Name: lo


Explanation of the above program:

Note: In above program, it is not showing more network interfaces because it runs virtually. But if we run same code on system then we can see many network interfaces and its information.



We can see in the below image, the original result on system:


Article Tags :