How can I obtain an IP address from a host name?

Brandon Rohlfs

The InetAddress class gives the programmer a solution to this problem through a process called resolution. When an IP address is obtained from an host name we call this Host Name Resolution with the opposite (obtaining a host name from an IP address) called Reverse Host Name Resolution The process of resolution is accomplished via various services such as Domain Name System (DNS) and Network Information Service (NIS).

InAddress provides various static methods, which return an initialized instance.

static InetAddress getByName(String host)
static InetAddress getByAddress(byte[] host)
static InetAddress[] getAllByName(String host)
static InetAddress getLocalHost() 

The method that we want to use is the first one which simply takes a host name as an arguement in the form of a String.

// Host name resolution 
InetAddress ina = InetAddress.getByName("www.sun.com");
System.out.println(ina2.getHostAddress()); //
The hostname can even be represented as the loopback address.
InetAdress ina = InetAddress.getByName("localhost"); 
System.out.println(ina2.getHostAddress()); //
if(ina.isLoopbackAddress()){ // true 
 System.out.println(ina.getHostAddress() + "is a loopback!");

InetAddress Caching

InetAddress caches positive resolutions indefinetly. The reason for the positive cache is to guard against such attacks as spoofing. Negative caching is also used to improve performance with a default cache time of 10 seconds. Say we are trying to do a reverse host name lookup.

InetAddress ina = InetAddress.getByName(""); 
After running the previous code snippet we see that the resolves to and not www.sun.com. It is only after a positive host name resolution that an InetAddress initialized from an IP address yields a host name.
ina1 = InetAddress.getByName("www.sun.com"); 
System.out.println(ina1.getHostAddress()); // 
ina2 = InetAddress.getByName(""); 
System.out.println(ina2.getHostName()); //www.sun.com