How do I retrieve network interface information using NetworkInterface in Java?

To retrieve network interface information using the NetworkInterface class in Java, you can use the java.net package which provides the NetworkInterface class. This class allows you to get information about network interfaces such as IP addresses, display names, names, hardware (MAC) addresses, and more.

Here is an example illustrating how to retrieve information about all network interfaces available on the machine:

Code Example

package org.kodejava.net;

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

public class NetworkInterfaceInfo {
   public static void main(String[] args) {
      try {
         // Get all network interfaces
         Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

         while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();

            // Display interface name and display name
            System.out.println("Interface Name: " + networkInterface.getName());
            System.out.println("Display Name: " + networkInterface.getDisplayName());

            // Display MAC address
            byte[] mac = networkInterface.getHardwareAddress();
            if (mac != null) {
               StringBuilder macAddress = new StringBuilder();
               for (int i = 0; i < mac.length; i++) {
                  macAddress.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
               }
               System.out.println("MAC Address: " + macAddress.toString());
            } else {
               System.out.println("MAC Address: Not available");
            }

            // Display the IP addresses associated with this interface
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
               InetAddress inetAddress = inetAddresses.nextElement();
               System.out.println("IP Address: " + inetAddress.getHostAddress());
            }

            // Display other information
            System.out.println("MTU: " + networkInterface.getMTU());
            System.out.println("Is Loopback: " + networkInterface.isLoopback());
            System.out.println("Is Up: " + networkInterface.isUp());
            System.out.println("Is Virtual: " + networkInterface.isVirtual());
            System.out.println("Supports Multicast: " + networkInterface.supportsMulticast());
            System.out.println("--------------------------------------------");
         }
      } catch (SocketException e) {
         e.printStackTrace();
      }
   }
}

Explanation:

  1. Getting All Network Interfaces:
    The NetworkInterface.getNetworkInterfaces() method retrieves an enumeration of all network interfaces available on the machine.

  2. Retrieving Basic Information:

    • getName(): Returns the name of the network interface.
    • getDisplayName(): Returns a user-readable name for the network interface.
  3. Retrieving the MAC Address:
    • getHardwareAddress(): Returns the hardware (MAC) address of the network interface as an array of bytes.
  4. Retrieving IP Addresses:
    • getInetAddresses(): Returns all assigned IP addresses (both IPv4 and IPv6) for this interface.
  5. Flags and Features of the Interface:
    • isUp: Checks if the network interface is up and operational.
    • isLoopback: Checks if the interface is a loopback interface.
    • isVirtual: Checks if it is a virtual interface.
    • supportsMulticast: Indicates whether the interface supports multicasting.
    • getMTU: Returns the Maximum Transmission Unit (MTU) of the interface.
  6. Handling SocketException:
    Accessing network interfaces and their properties might throw a SocketException, so wrap the logic in a try-catch block.

Output Example (Depending on Your Machine’s Network Setup)

Interface Name: ethernet_32768
Display Name: Intel(R) Ethernet Connection (18) I219-LM
MAC Address: C4-EF-BB-80-01-D0
IP Address: fe80:0:0:0:8e43:dfa1:eb66:b106%ethernet_32768
MTU: 1500
Is Loopback: false
Is Up: false
Is Virtual: false
Supports Multicast: true
--------------------------------------------
Interface Name: loopback_0
Display Name: Software Loopback Interface 1
MAC Address: Not available
IP Address: 0:0:0:0:0:0:0:1
IP Address: 127.0.0.1
MTU: 1500
Is Loopback: true
Is Up: true
Is Virtual: false
Supports Multicast: true
--------------------------------------------

This code allows you to inspect all network interfaces, their properties, and associated information in Java.

How do I work with InetAddress to resolve IP addresses in Java?

In Java, InetAddress is part of the java.net package and is used to handle IP addresses, both IPv4 and IPv6. It provides methods to resolve hostnames to IP addresses and vice versa, as well as to work with local and remote host information. Here’s a detailed explanation of how to work with InetAddress to resolve IP addresses:

Basic Workflow with InetAddress

  • Import the Necessary Package
import java.net.InetAddress;
import java.net.UnknownHostException;
  • Resolve a Hostname to an IP Address Use InetAddress.getByName(String hostname) to find the IP address of a given hostname:
try {
   InetAddress address = InetAddress.getByName("www.example.com");
   System.out.println("Host Name: " + address.getHostName());
   System.out.println("IP Address: " + address.getHostAddress());
} catch (UnknownHostException e) {
   System.err.println("Host not found: " + e.getMessage());
}
  • Get the Local Host Address Use InetAddress.getLocalHost() to retrieve the IP address of your local machine:
try {
   InetAddress localHost = InetAddress.getLocalHost();
   System.out.println("Local Host Name: " + localHost.getHostName());
   System.out.println("Local IP Address: " + localHost.getHostAddress());
} catch (UnknownHostException e) {
   System.err.println("Unable to get local host address: " + e.getMessage());
}
  • Resolve All IP Addresses for a Hostname Some hostnames might resolve to multiple IP addresses (e.g., websites using load balancing). Use InetAddress.getAllByName(String hostname) to get all associated IPs:
try {
   InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
   for (InetAddress address : addresses) {
       System.out.println("IP Address: " + address.getHostAddress());
   }
} catch (UnknownHostException e) {
   System.err.println("Host not found: " + e.getMessage());
}
  • Work with the Loopback Address You can retrieve and work with the default loopback address (127.0.0.1 or ::1):
InetAddress loopback = InetAddress.getLoopbackAddress();
System.out.println("Loopback Address: " + loopback.getHostAddress());
  • Check Reachability Use InetAddress.isReachable(int timeout) to check if an address is reachable (via ICMP ping-like mechanism):
try {
   InetAddress address = InetAddress.getByName("www.example.com");
   if (address.isReachable(5000)) { // Timeout in milliseconds
       System.out.println(address + " is reachable.");
   } else {
       System.out.println(address + " is not reachable.");
   }
} catch (Exception e) {
   System.err.println("Error checking reachability: " + e.getMessage());
}
  • Create an InetAddress from an IP String If you already have an IP address in string form and want to create an InetAddress object:
try {
   InetAddress address = InetAddress.getByName("192.168.0.1");
   System.out.println("Host Name: " + address.getHostName());
   System.out.println("IP Address: " + address.getHostAddress());
} catch (UnknownHostException e) {
   System.err.println("Invalid IP address: " + e.getMessage());
}

Useful Methods in InetAddress

Method Description
getByName(String host) Returns InetAddress for the given hostname or IP address.
getAllByName(String host) Returns all InetAddress objects for the given hostname.
getLocalHost() Fetches the local machine’s InetAddress.
getLoopbackAddress() Returns the loopback address (e.g., 127.0.0.1).
getHostName() Returns the hostname for the IP address.
getHostAddress() Gets the IP address as a string.
isReachable(int timeout) Checks if the address is reachable within a given timeout.
equals(Object obj) Compares two InetAddress objects.
hashCode() Generates the hash code for the InetAddress instance.

Common Use-Case Examples

Example 1: Resolving a Hostname

try {
    InetAddress address = InetAddress.getByName("www.example.com");
    System.out.println("IP Address: " + address.getHostAddress());
} catch (UnknownHostException e) {
    System.err.println("Unable to resolve host: " + e.getMessage());
}

Example 2: Listing All IPs for a Domain

try {
    InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
    for (InetAddress addr : addresses) {
        System.out.println(addr);
    }
} catch (UnknownHostException e) {
    System.err.println("Unable to resolve host: " + e.getMessage());
}

Example 3: Checking Local Host Information

try {
    InetAddress localHost = InetAddress.getLocalHost();
    System.out.println("HostName: " + localHost.getHostName());
    System.out.println("IP Address: " + localHost.getHostAddress());
} catch (UnknownHostException e) {
    System.err.println("Error: " + e.getMessage());
}

Notes:

  • In modern applications, DNS caching and network configurations can affect resolution.
  • InetAddress.getByName internally resolves the hostname using DNS.
  • For non-blocking or asynchronous networking, consider Java’s java.nio package.

With these explanations and examples, you should be able to handle IP address resolution reliably using InetAddress.

How do I convert raw IP address to String?

This example show you how to convert a raw IP address, an array of byte, returned by InetAddress.getAddress() method call to its string representation.

package org.kodejava.net;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class RawIPToString {
    public static void main(String[] args) {
        byte[] ip = new byte[0];
        try {
            InetAddress address = InetAddress.getLocalHost();
            ip = address.getAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String ipAddress = RawIPToString.getIpAddress(ip);
        System.out.println("IP Address = " + ipAddress);

        try {
            InetAddress address = InetAddress.getByName("google.com");
            ip = address.getAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        ipAddress = RawIPToString.getIpAddress(ip);
        System.out.println("IP Address = " + ipAddress);
    }

    /**
     * Convert raw IP address to string.
     *
     * @param rawBytes raw IP address.
     * @return a string representation of the raw ip address.
     */
    private static String getIpAddress(byte[] rawBytes) {
        int i = 4;
        StringBuilder ipAddress = new StringBuilder();
        for (byte raw : rawBytes) {
            ipAddress.append(raw & 0xFF);
            if (--i > 0) {
                ipAddress.append(".");
            }
        }
        return ipAddress.toString();
    }
}

This example will print something like:

IP Address = 30.30.30.60
IP Address = 142.251.10.113

How do I create port scanner program?

In this example you’ll see how to create a simple port scanner program to check the open ports for the specified host name.

package org.kodejava.net;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class PortScanner {
    public static void main(String[] args) throws Exception {
        String host = "localhost";
        InetAddress inetAddress = InetAddress.getByName(host);

        String hostName = inetAddress.getHostName();
        for (int port = 0; port <= 65535; port++) {
            try {
                Socket socket = new Socket(hostName, port);
                String text = hostName + " is listening on port " + port;
                System.out.println(text);
                socket.close();
            } catch (IOException e) {
                // empty catch block
            }
        }
    }
}

The result of the code snippet above are:

localhost is listening on port 21
localhost is listening on port 80
localhost is listening on port 135
localhost is listening on port 445
localhost is listening on port 3000
...
...
localhost is listening on port 63342
localhost is listening on port 63467
localhost is listening on port 64891
localhost is listening on port 64921
localhost is listening on port 65001

How do I get MAC address of a host?

Previously for obtaining a MAC address we need to use a native code as a solution. In JDK 1.6 a new method is added in the java.net.NetworkInterface class, this method is getHardwareAddress().

package org.kodejava.net;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MacAddress {
    public static void main(String[] args) {
        try {
            // InetAddress address = InetAddress.getLocalHost();
            InetAddress address = InetAddress.getByName("192.168.0.105");

            /*
             * Get NetworkInterface for the current host and then read
             * the hardware address.
             */
            NetworkInterface ni = NetworkInterface.getByInetAddress(address);
            if (ni != null) {
                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {
                    /*
                     * Extract each array of mac address and convert it
                     * to hexadecimal with the following format
                     * 08-00-27-DC-4A-9E.
                     */
                    for (int i = 0; i < mac.length; i++) {
                        System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
                    }
                } else {
                    System.out.println("Address doesn't exist or is not accessible.");
                }
            } else {
                System.out.println("Network Interface for the specified address is not found.");
            }
        } catch (UnknownHostException | SocketException e) {
            e.printStackTrace();
        }
    }
}