java.net.InetAddressis 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.
* This class provides a very simple example of using the java.net.InetAddress
* class. It demonstrates methods on the java.net.InetAddress class such as
* getLocalHost(), getHostName(), getHostAddress(), and getAddress().
* In addition this class demonstrates the need to catch the checked exception
* java.net.UnknownHostException (or an exception above it such as Exception).
public class INetAddressExample
* Run simple demonstration of the usefulness of the java.net.InetAddress
* @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( "Doh!! Unknown Host ("
+ "): " + unknownHostException.getMessage() );
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
java.net.UnknownHostExceptionand the code will work as well. Either way the exception must be caught because
UnknownHostExceptionis a checked exception.