How to get the Server IP Address and Hostname in Java

The following programming tutorial will demonstrate how we can write a Java program to get the Current Server IP Address and Hostname. This tutorial falls under the domain of Networking using Java and uses several basic but key concepts of networking such as IP (Internet Protocol ) Addresses, hostname, etc. The program makes use of the InetAddress class to represent an Internet Protocol Address.

An IP Address is assigned to each device connected in a network of computers, networking devices, etc. It is a 32-bit address given to each device in the network and can be used to identify devices within the network. There is a need to write programs that can execute on various devices at once; this is known as network programming.

Java Program to get the Server IP Address and Hostname

import java.net.*;

public class JavaProg {

    public static void main(String[] args) {
       
        InetAddress currentIPAddress; //InetAddress Variable 
        
        try {
                currentIPAddress = InetAddress.getLocalHost(); //getLocalHost() method returns the Local Hostname and IP Address
                System.out.print("The Current Hostname and Server IP Address is:" + currentIPAddress);       
        } 
        catch (UnknownHostException ex) {
 
            ex.printStackTrace();
        }
    }
}

Output

Java Program to get the Server IP Address and Hostname

The important method used in the program is:

  • getLocalHost() – this method returns the InetAddress instance that contains the IP Address and the hostname

The concept of exception handling has also been implemented using the try and catch block. They are used to handle unexpected runtime exceptions. The catch block includes “UnknownHostException” which handles the exception where the localhost cannot be resolved in a InetAddress instance.

Leave a Reply

Your email address will not be published. Required fields are marked *