Java Get Local Host IP Address

Tags: InetAddress IP IPUtils

In this Java tutorial, we learn how to write a Java utility class to get the local host IP address in Java programming language.

How to get local host IP address in Java

At this first step, create a new Java class named IPUtils.

In the new class, implement a static method named getLocalHostIPAddress(), to get local host IP address we can invoke the InetAddress.getLocalHost() static method to get the adress local host and call method getHostAddress() to return the IP address String value as the following Java code.

IPUtils.java

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

public class IPUtils {

    /**
     * This method to return the local host IP address
     * @return the IP address
     */
    public static String getLocalHostIPAddress() {
        String localhostIP = null;
        try {
            localhostIP = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return localhostIP;
    }
}

In the following example Java code, we learn how to use the above IPUtils.getLocalHostIPAddress() static method to get the local host IP address in Java program.

GetLocalhostIPAddressExample.java

public class GetLocalhostIPAddressExample {
    public static void main(String... args) {
        // Get Local Host IP Address
        String localhostIP = IPUtils.getLocalHostIPAddress();

        System.out.println("IP Address: " + localhostIP);
    }
}
The output as below.
IP Address: 172.24.0.1

Happy Coding 😊

Java Get Local Host Name

Spring Boot Web Get Client IP Address

Java Get Current Thread Name and ID