Get IP address from hostname

In this example we shall show you how to retrieve the IP address from the hostname of a specific host. To get the IP address using a hostname one should perform the following steps :

  • Retrieve the Address object of the specific host. This object contains all address related information about the specific host
  • Use the getAddress() API method to get a byte array representation of the IP address of the specific host. In order to convert the byte array representation to a more readable one you may perform a conversion like the one shown in the code snippet below

If the specific host address exists and there is no connectivity issues between the client and the host machines then you should be able to get the hostname from the designated host IP address.

package com.javacodegeeks.snippets.core;


public class GetIPAddressFromHostname {
	public static void main(String[] args) {
		try {
			InetAddress inetAddr = InetAddress.getByName("");
			byte[] addr = inetAddr.getAddress();

			// Convert to dot representation
			String ipAddr = "";
			for (int i = 0; i < addr.length; i++) {
				if (i > 0) {
					ipAddr += ".";
				ipAddr += addr[i] & 0xFF;
			System.out.println("IP Address: " + ipAddr);
		catch (UnknownHostException e) {
			System.out.println("Host not found: " + e.getMessage());


This was an example of how to get the IP address from the hostname of a specific host in Java.


IP Address:

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button