This blog helps you to get the hostname and IP address of where the program is running. It uses the InetAddress class of Java which uses the Internet Protocol address.
While development and testing most developer uses own computer or laptop to run the program. so the program will provide the hostname of the system where this code is executed.
This code uses java.net library of java to get the Hostname.
Here is the code which get hostname using Java.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.cbm.hostname ;
import java.net.InetAddress ;
import java.net.UnknownHostException ;
public class JavaGetHostName {
public static void main ( String[] args) throws UnknownHostException{
InetAddress inetAddress = InetAddress. getLocalHost ();
String hostname = inetAddress. getHostName ();
System. out . println ( "Hostname of current host: " + hostname);
System. out . println ( "IP address of current host: " + inetAddress);
}
}
Output:
Hostname of current host: DESKTOP-TTSBKDU
IP address of current host: DESKTOP-TTSBKDU/192.168.0.110
InetAddress getLocalHost()
getLocalHost() of InetAddress return the local host It get the name from the system and assigned to InetAddress.
This method throws UnknownHostException incase if system is not able to retrieve the hostname or not able to associate with IP address.
Code with Exception Handling
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.net.InetAddress ;
import java.net.UnknownHostException ;
public class JavaGetHostName {
public static void main ( String[] args) {
try {
InetAddress inetAddress = InetAddress. getLocalHost ();
String hostname = inetAddress. getHostName ();
System. out . println ( "Hostname of current host: " + hostname);
System. out . println ( "IP address of current host: " + inetAddress);
} catch ( UnknownHostException exception) {
System. out . println ( "Exception:->" + exception. getMessage ());
}
}
}
More article to read:
String to Char Array Java
Useful tool to https://codebeautify.org/hostname-to-ip
Sharing is caring!