java get hostname

Here’s a guide with multiple examples in JAVA to get hostname or IP address from URL or localhost using JAVA API.

We get a dedicated JAVA class to help with it

How to get the localhost address?

Use method It returns the localhost address. It retrieves the name of the system host and resolves it into an InetAddress.

How to get the IP?

Use method It returns the IP address of the host. In case of localhost, it returns

How to get website hostname URL?

Use method It gives the URL/hostname of the above-retreived IP address.

Sample code snippet :

package com.mytrashcode;


class HostNameExample {
public static void main(String args[]) throws Exception {
try {
   InetAddress inetAddress = InetAddress.getLocalHost();
   System.out.println("IP Address:- " + inetAddress.getHostAddress());
   System.out.println("Host Name:- " + inetAddress.getHostName());
   System.out.println("Localhost:- " + inetAddress.getLocalHost());
  } catch (UnknownHostException e) {
Also read: : Advantages of Golang over Java and Python

Result :

IP Address:-
Host Name:- mytrashcode
Localhost:- localhost


inetAddress.getHostName()); is bound to fail in some circumstances:

  • The IP address might not get resolved due to a bad DNS setup.
  • A DNS name can have many aliases as CNAMEs.
  • A host can have many different IP addresses. Two common causes are:
    • One ethernet port has several “logical” IP addresses or the computer has several ethernet ports.
    • It is configurable whether they share an IP or have different IPs. This is called “multihomed”.
  •  A simple example of load-balancing where one Name in DNS can resolve to several IP Addresses. And not all of those addresses might be located on the same computer.
  • Dynamic IP addresses can be one more critical case to handle.
Also check :   Best class to java decompilers : Try online or download free

Comment and let us know if this java get hostname guide helped you or in case you would love to see some other guide on our blog.

Leave a Reply

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