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
OUTPUT of the above code
Explanation of the code
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){
unknownHostException.printStackTrace();
}
}
}
IP Address: 192.168.1.104 Hostname: DESKTOP-LINB67D
- 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 ofInetAddress
, namedinetAddress
, 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 as192.168.1.104
. - The hostname for the current machine is retrieved using
inetAddress.getHostName()
method which is printed asDESKTOP-LINB67D
. This happens to be the "Computer Name" of the Windows 10 laptop on which I executed the above code.