0% found this document useful (0 votes)
108 views

Java Program To Display Hostname and IP Address

This Java code displays the hostname and IP address of the local host by getting the InetAddress of the local host, catching any exceptions. It prints the host address and name by calling the getHostAddress() and getHostName() methods on the InetAddress instance.

Uploaded by

yamela rodriguez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views

Java Program To Display Hostname and IP Address

This Java code displays the hostname and IP address of the local host by getting the InetAddress of the local host, catching any exceptions. It prints the host address and name by calling the getHostAddress() and getHostName() methods on the InetAddress instance.

Uploaded by

yamela rodriguez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

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.

You might also like