Java program to display Hostname and IP address


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

Example

 Live Demo

import java.net.*;
public class Demo{
   public static void main(String[] args){
      try{
         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.");
      }
   }
}

Output

The IP address is : 127.0.0.1
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.

Updated on: 08-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements