Display Hostname and IP Address in Java



In this article, we will learn to display the Hostname and IP address using Java. To display the Hostname and IP address we will be using the InetAddress class from the java.net package. We'll write a simple program to fetch and print this information, and perform the exception handling to catch the exception if the data isn't found.

Problem Statement

Write a program in Java to display the Hostname and IP address. Below is a demonstration of the same ?

Output 

The IP address is : 127.0.0.1
The host name is : jdoodle

Steps to display Hostname and IP address

Following are the steps to display the Hostname and IP address ?

  • First, we will import all the classes from the java.net package
  • Initialize the Demo class.
  • We will be using a try-catch block to handle UnknownHostException if the local address cannot be found.
  • Get the local host's address and print the IP address.
  • Print host name by using the InetAddress object.

Java program to display Hostname and IP address

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

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

Code Explanation

A class named Demo contains the main function. A ?try' and ?catch' block is defined in this main function. 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: 2024-08-28T21:18:08+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements