JB Header
How to get IP Address and Hostname in Java using InetAddress with example
This tutorial explains how to get the IP address and hostname of the localhost or server machine on which the JVM is running using java.net.InetAddress class. It first shows a java code example for fetching of IP address and hostname using InetAddress.getIpAddress() and InetAddress.getHostname() methods respectively, and then explains the code.

Java code to get IP Address and Hostname
package com.javabrahman.misc;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IpAddress {
  public static void main(String args[]){
    try {
      InetAddress inetAddress = InetAddress.getLocalHost();
      System.out.println("IP Address: "+inetAddress.getHostAddress());
      System.out.println("Hostname: "+inetAddress.getHostName());
    }catch(UnknownHostException unknownHostException){
 OUTPUT of the above code
IP Address:
Explanation of the code
  • An instance of java.net.InetAddress encapsulates an Internet Protocol Address, commonly known as an IP Address, in Java. Along with the IP Address, an InetAddress instance may hold the hostname corresponding to the IP address as well.
  • In the above code, first InetAddress.getLocalHost() method is used to get an instance of InetAddress, named inetAddress, holding the IP address information for the machine on which the JVM is running.
  • The actual value of the IP Address is then retreived using inetAddress.getHostAddress() method which is printed as
  • The hostname for the current machine is retrieved using inetAddress.getHostName() method which is printed as DESKTOP-LINB67D. This happens to be the "Computer Name" of the Windows 10 laptop on which I executed the above code.