Skip to main content

Java InetAddress Class

Introduction to Java InetAddress Class

In the world of Java networking, the InetAddress class plays a vital role. An InetAddress object encapsulates an Internet Protocol (IP) address, which is a numerical label assigned to each device participating in a computer network. This article aims to introduce you to the InetAddress class in Java, its methods, and how to effectively use it in your networking projects.

What is the InetAddress Class?

The InetAddress class in Java is part of the java.net package. It has no visible constructor; that is, you cannot use the new keyword to create a new instance of this class. Instead, instances are created through the class methods provided, like getLocalHost(), getByName(String host), and getAllByName(String host).

This class provides methods to get the IP of any host name, for example, www.google.com, www.facebook.com, etc.

Methods of the InetAddress Class

Here are some commonly used methods of the InetAddress class:

  • public static InetAddress getByName(String host) throws UnknownHostException: Returns the InetAddress object associated with the given host name.
  • public static InetAddress getLocalHost() throws UnknownHostException: Returns the InetAddress object associated with the local host.
  • public String getHostName(): Returns the host name of the IP address.
  • public String getHostAddress(): Returns the IP address in string format.

Working with InetAddress Class

Let’s see a simple example of how to use the InetAddress class.

import java.net.*;  

public class InetAddressExample {
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.google.com");

System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
} catch(Exception e){
System.out.println(e);
}
}
}

In the above code, we are getting the IP address of www.google.com using the InetAddress.getByName() method, and then printing the host name and IP address.

Summary

In this article, we've covered the basics of the InetAddress class in Java and its common methods. Remember, the InetAddress class is part of the java.net package, and it's used to encapsulate both the numerical IP address and the domain name for that address.

Learning about the InetAddress class is your first step towards mastering Java networking. This class forms the basis of communication over the network in Java, and understanding it will help you significantly as you delve deeper into network programming.

In the next part of our Java networking series, we will continue to explore more about networking in Java, including topics like URL, TCP sockets, and server sockets. But for now, try to get comfortable with the InetAddress class and don't hesitate to experiment with it on your own. Happy coding!