The InetAddress class can be used to perform Domain Name Server (DNS) lookups. For example, you can call the static InetAddress.getByName("www.teamcakes.com") to retrieve an InetAddress object for 'www.teamcakes.com'. This object would contain the canonical name, host name, and ip address of 'www.teamcakes.com'.

The DnsTest class below demonstrates InetAddress.getLocalHost(), which obtains an Internet Address for your local host. It also demonstrates InetAddress.getByName("www.google.com"), which gives an Internet Address object for 'www.google.com'. However, it should be noted that a DNS name can map to multiple servers, and the InetAddress.getAllByName("www.google.com") call retrieves an array of InetAddress objects that represent all of the 'www.google.com' servers retrieved from DNS.

As you can see, the InetAddress class allows us to perform DNS lookups and retrieve canonical host names, host names, and IP addresses. The results above show us that multiple servers can be represented by one host name, and these can be distinguished by their different IP (host) addresses and canonical host names.

Just as an aside, what happens if we try doing a lookup on a host that doesn't exist, such as: InetAddress.getByName("www.this-host-does-not-exist.com")? An UnknownHostException is thrown, as shown below.

java.net.UnknownHostException: www.this-host-does-not-exist.com: www.this-host-does-not-exist.com
at java.net.InetAddress.getAllByName0(InetAddress.java:1128)
at java.net.InetAddress.getAllByName0(InetAddress.java:1098)
at java.net.InetAddress.getAllByName(InetAddress.java:1061)
at java.net.InetAddress.getByName(InetAddress.java:958)
at test.DnsTest.main(DnsTest.java:12)