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 "" 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
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:



Popular posts from this blog

How to Timeout JDBC Queries