Home » Core Java » net » InetAddress » Get IP address from hostname

About Ilias Tsagklis

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

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;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetIPAddressFromHostname {
	
	public static void main(String[] args) {
		
		try {
			
			InetAddress inetAddr = InetAddress.getByName("javacodegeeks.com");
			
			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.

Output:

IP Address: 216.239.34.21
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of