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.getHostname() methods respectively, and then explains the code.
- An instance of
java.net.InetAddressencapsulates 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, 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.