Java Get Local Host Name
Tags: InetAddress
In this Java tutorial, we learn how to write Java program to get the local host name in Java programming language.
How to get the local host name in Java
First step, create a new Java class named LocalHostUtils. In this new class, implement a static method named getLocalHostName(), to get the local host name we can use the InetAddress.getLocalHost().getHostName() method as Java code below.
LocalHostUtils.java
import java.net.InetAddress;
import java.net.UnknownHostException;
public class LocalHostUtils {
/**
* This method to get the local host name.
* @return the local host name.
*/
public static String getLocalHostName() {
String localhostMName = null;
try {
localhostMName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return localhostMName;
}
}
In the following example Java program, we learn how to the above LocalHostUtils.getLocalHostName() static method in Java program.
GetLocalHostNameExample.java
public class GetLocalHostNameExample {
public static void main(String... args) {
// Get Local Host Name
String hostName = LocalHostUtils.getLocalHostName();
System.out.println("Local host name: " + hostName);
}
}
Local host name: simplecomputer
Happy Coding 😊
Related Articles
Java Get Local Host IP Address