Thursday, July 22, 2021

How to Convert Hostname to IP Address in Java - InetAddress Example

Hello guys, today, I am going to teach you about one interesting class from java.net package, the InetAddress. If you have never used this class before, let me tell you that it's an abstraction to represent an Internet address and it encapsulates both hostname and IP address. Since converting an IP address to hostname or hostname to IP address is a very common requirement, Java developers should know about this class, and, in general about java.net package, which contains many other useful class for networking and client-server applications. So, what is the best way to learn new APIs like java.net? Well, by writing small programs like this, which has a small focus and let you explore things. They are super useful and that's how I have learned the majority of Java API.

In this example, I have used the main() method to execute the program but if you want you can also start writing the JUnit test as suggested in Test Driven for exploring Regular Expression APIs like Matcher and Pattern classes and methods like find(). If you haven't read that book, make an effort to read it this weekend, it's an awesome book and you will be a better Java developer after reading that book.

Anyway, coming back to the task in hand, you need to write a Java program to convert hostname to IP address in Java. Though you can hardcode the hostname for testing purpose, I have made this program more interactive, which means you can run this program and enter the hostname from the command prompt.

For Beginners, I recommend this approach because that interactiveness gives the feeling that something is running and working and it also allows you to test by giving random input and getting immediate feedback.

Though, for Intermediate programmers, I recommend writing JUnit tests with predefined input as that's how professional Java developers write code. Though, if you don't know much about JUnit, I suggest you join a course like Learn Unit Testing with JUnit & Mockito in 30 Steps on Udemy. That's will also make you a better Java developer.




How to Convert Hostname to IP Address in Java

Now that you know that you can use InetAddress class from java.net package to convert hostname to IP address, let's write our Java program. Apart from that bit, we also need to know how to get user input from the command line or console and how to print values back to console.

I am sure you know how to do that but if you don't let me tell you that you can use the Scanner class from java.util package to read the user input from the command line. This class also does a lot more than just reading input, it can also convert the input into the data type you want.

For example, if you enter "111" on a console then it can read it as a String or as an Integer. In this case, we don't need to do anything special as hostnames are going to be String and Scanner.nextLine() returns String.

Now, coming back to printing the output into the console, you can use the plain old System.out.println() method, the first method I learned on Java. Btw, if you don't much about these basic concepts then I also suggest you go through a comprehensive Java course like The Complete Java MasterClass to learn them in a structured way. It's also the most up-to-date class and updated for Java 12.

How to Convert Hostname to IP Address in Java


And, here is our complete Java program to convert hostname to IP address, you can run it either on the command line or on your favorite ides like Eclipse, IntellJIDEA or NetBeans.

Java Program to convert hostname to IP Address

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Scanner;
 
 
/**
 * Java program to get IP address from hostname in Java
 *
 * @author WINDOWS 8
 *
 */
 
public class HelloAndroid {
 
    public static void main(String args[]) {
 
        // Creating Scanner to read input from Console
        Scanner console = new Scanner(System.in);
 
 
        System.out.println("Please enter hostname to find IP address");
        String hostname = console.nextLine();
 
 
        // Use static method getByName() to get InetAddress of host
        InetAddress inet = null;
 
        try {
            inet = InetAddress.getByName(hostname);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
 
        }
 
 
        // Getting IP address from hostname in Java
        String IPAddress = inet.getHostAddress();
 
        System.out.printf("IP address of host %s  is %s %n", hostname, IPAddress);
 
    }
 
}
 
Output:
Please enter the hostname to find the IP address
HP
The IP address of host HP  is 192.168.1.4 


That's all about how to find the IP address from hostname in Java. This kind of small programs will help you to learn and understand JDK API better. As you have learned some of the key classes from java.net package in this program like InetAddress which contains both hostname and IP Address and abstraction to represent an internet address.


Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any issue on understanding this program or running it from the command line or Eclipse, please drop a note and I'll try my best to help you.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.