Java - How to find the IP Address of a host in Java ?

In Java, if you are looking to resolve an IP Address from the given hostname, then you can leverage the capabilities provided by InetAddress. It belongs to the "java.net" package and provides various utilities related to resolving addresses and IPs.

The following code e.g. gives you back an IP address for the provided hostname.

System.out.println(  InetAddress.getByName("myhost").getHostAddress()  );


Note that getByName throws an UnknownHostException if it is unable to resolve the host.

A few other interesting methods available from InetAddress are :

getCanonicalHostName - This returns the fully qualified hostname, including the domain name.
getHostName - To get the hostname for a given IP address.
getLocalHost - To get the hostname or IP Address of the local machine.
getLoopBackAddress - To get the loopback address of the local machine.
isReachable - To check if the address is reachable within the provided timeout

The following code snippet shows these methods in use:

//Prints the FQN for myhost
System.out.println(  InetAddress.getByName("myhost").getCanonicalHostName()  );

//Prints the hostname for 11.22.1.38
System.out.println(  InetAddress.getByAddress(new byte[]{11, 22, 1, 38}).getHostName()  );

//Prints the hostname for the local machine
System.out.println(  InetAddress.getLocalHost().getHostName  );

//Prints the loopback address of the local machine.
System.out.println(  InetAddress.getLoopbackAddress().getHostAddress()  );

//Prints true if the machine is reachable.
System.out.println(  InetAddress.getByName("myhost").isReachable(10000)  );


The result would be:
myhost.codelooru.com

myhost.codelooru.com

mylocalhost

127.0.0.1

true