Easy Tutorial
❮ Java9 Optional Class Improvements Method Varargs ❯

Java Example - Getting Local IP Address and Hostname

Java Examples

The following example demonstrates how to use the getLocalAddress() method of the InetAddress class to get the local IP address and hostname:

Main.java File

import java.net.InetAddress;

public class Main {
   public static void main(String[] args) 
   throws Exception {
      InetAddress addr = InetAddress.getLocalHost();
      System.out.println("Local HostAddress: 
      " + addr.getHostAddress());
      String hostname = addr.getHostName();
      System.out.println("Local host name: " + hostname);
   }
}

The output of the above code is:

Local HostAddress: 192.168.1.4
Local host name: harsh

Java Examples

❮ Java9 Optional Class Improvements Method Varargs ❯