In this post, I will be sharing the Java program to get the local IP Address and Hostname of the local computer.

java.net.InetAddress class represents an Internet Protocol (IP) address in Java.

Read Also: How to Get Environment Variable in Java

InetAddress.getLocalHost() returns the IP address of the current server running the Java application.

InetAddress.getHostName() returns the Hostname of the current server name.

Java Program to get IP address and Hostname

 import java.net.InetAddress;

public class GetIPAddressAndHostname {
public static void main(String args[]) throws Exception {

String hostname;
InetAddress ip;

/* public static InetAddress.getLocalHost() throws
* UnknownHostException and returns the address of
* the localhost.
*/

ip = InetAddress.getLocalHost();

/* public String InetAddress.getHostName() fetches
* the Hostname of this IP address.
*/

hostname = ip.getHostName();

// Printing the IP address and Hostname
/* public String getHostAddress() returns the textual presentation
* of the IP address string.
*/

System.out.println("IP Address is: "+ ip.getHostAddress());
System.out.println("Hostname is: "+ hostname);
}
}

Output:
IP Address is: 192.168.1.101
Hostname is: Subham-Mittal

Reference:
Oracle Java docs