Monday, January 28, 2008

InetAddress Example

The Java class is a useful class that has been available since JDK 1.0. It has been updated in newer versions of Java, but the core class has been around since JDK 1.0.

Here is a simple code example that demonstrates use of this class and the handy information it provides.

package net.sample;

 * This class provides a very simple example of using the
 * class.  It demonstrates methods on the class such as
 * getLocalHost(), getHostName(), getHostAddress(), and getAddress().
 * In addition this class demonstrates the need to catch the checked exception
 * (or an exception above it such as Exception).
public class INetAddressExample
    * Run simple demonstration of the usefulness of the
    * class.
    * @param aArgs The command line arguments; none expected.
   public static void main(final String[] aArgs)
      InetAddress localhost = null;
         localhost = InetAddress.getLocalHost();
         System.out.println( "InetAddress: " + localhost );
         System.out.println( "\ttoString: " + localhost.toString() );
         System.out.println(  "\tCanonicalHostName: "
                            + localhost.getCanonicalHostName() );
         System.out.println( "\tHost Name: " + localhost.getHostName() );
         System.out.println( "\tHost Address: " + localhost.getHostAddress() );
         System.out.println( "\tHost Bytes: " + localhost.getAddress() );
         System.out.println( "\tHash Code: " + localhost.hashCode() );

         // We will now force an UnknownHostException to be thrown.
         InetAddress nonExistent = InetAddress.getByName("nada");
         System.out.println( "Host is: " + nonExistent );  // won't get here!
      catch (/*UnknownHost*/Exception unknownHostException) // checked exception
         System.err.println(  "D'oh!! Unknown Host ("
                            + unknownHostException.getClass().toString()
                            + "): " + unknownHostException.getMessage() );

An adapted version of the class shown above is now available on GitHub.

The output from running this is shown in the following screen shot:

I intentionally commented out the UnknownHost portion of the exception to capture a general exception. However, you can uncomment this out along with the import statement for and the code will work as well. Either way the exception must be caught because UnknownHostException is a checked exception.

No comments: