How to get IP address of a Host in Java?

The InetAddress class in Java serves the purpose of performing DNS lookups. It offers functionality to obtain the IP address of a given host name, whether it is a machine name like "mail.yahoo.com" or a textual representation of an IP address. By utilizing methods provided by the java.net.InetAddress class, such as getByName(), developers can retrieve the IP address associated with various host names like www.yahoo.com or www.facebook.com.

InetAddress has no public constructor, so you must obtain instances via a set of static methods.

InetAddress ip = InetAddress.getLocalHost();

Java InetAddress Class is used to encapsulate the two thing.

  1. Numeric IP Address
  2. The domain name for that address

1. getLocalHost(): The getLocalHost() method in Java returns an InetAddress object that represents the local host, including its name and address. However, if the method fails to determine the host name, it throws an UnknownHostException. This exception indicates that the host name could not be resolved or that the local host information is not available.

InetAddress ip = InetAddress.getLocalHost();

2. getByName(): The getByName() method in Java's InetAddress class is used to obtain an InetAddress object for a given host name passed as a parameter. It retrieves the IP address associated with the host name. However, if the method is unable to resolve the host name or find the corresponding IP address, it throws an UnknownHostException. This exception indicates that the host name could not be resolved or that the IP address is not available for the given host name.

InetAddress address = InetAddress.getByName("localhost");
Example
import java.net.InetAddress; import java.net.UnknownHostException; public class TestClass { public static void main(String[] args) { try{ InetAddress ip = InetAddress.getLocalHost(); String hostname = ip.getHostName(); System.out.println("IP address : " + ip); System.out.println("Computer Name : " + hostname); InetAddress address = InetAddress.getByName("localhost"); System.out.println(address.toString()); }catch(Exception ex){ System.out.println(ex); } } }

Conclusion

You can obtain the IP address of a host using the InetAddress class from the java.net package. By providing the host name, you can use the getByName() method to get the corresponding IP address. Additionally, you can use getHostAddress() to retrieve the IP address as a string for further processing or display.