Java program to display Hostname and IP address

To display Hostname and IP address in Java, the code is as follows −


 Live Demo

public class Demo{
   public static void main(String[] args){
         InetAddress my_address = InetAddress.getLocalHost();
         System.out.println("The IP address is : " + my_address.getHostAddress());
         System.out.println("The host name is : " + my_address.getHostName());
      catch (UnknownHostException e){
         System.out.println( "Couldn't find the local address.");


The IP address is :
The host name is : jdoodle

A class named Demo contains the main function. In this main function, a ‘try’ and ‘catch’ block is defined. In the ‘try’ block, an instance of InetAddress is created and the ‘getLocalHost’ function is used to get the Host address and host name of the InetAddress instance. In case one of the attributes is not found, the ‘catch’ block defines catching the exception and printing the relevant message on the console.