Ways in JAVA to get hostname, localhost and IP Address

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 java.net.InetAddress

How to get the localhost address?

Use method java.net.InetAddress.getLocalHost(). 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 java.net.InetAddress.getHostAddress(). It returns the IP address of the host. In case of localhost, it returns 127.0.0.1

How to get website hostname URL?

Use method java.net.InetAddress.getHostName(). It gives the URL/hostname of the above-retreived IP address.

Sample code snippet :

package com.mytrashcode;

import java.net.InetAddress;

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) {
            e.printStackTrace();
  }
}
}

[su_label type=”info”]Also read: [/su_label] : Advantages of Golang over Java and Python

Result :

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

NOTE :

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.

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 Comment