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.
packagecom.cbm.hostname;importjava.net.InetAddress;importjava.net.UnknownHostException;publicclassJavaGetHostName{publicstaticvoidmain(String[]args)throwsUnknownHostException{InetAddressinetAddress=InetAddress.getLocalHost();Stringhostname=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.
importjava.net.InetAddress;importjava.net.UnknownHostException;publicclassJavaGetHostName{publicstaticvoidmain(String[]args){try{InetAddressinetAddress=InetAddress.getLocalHost();Stringhostname=inetAddress.getHostName();System.out.println("Hostname of current host: "+hostname);System.out.println("IP address of current host: "+inetAddress);}catch(UnknownHostExceptionexception){System.out.println("Exception:->"+exception.getMessage());}}}
Sharing is caring!