The InetAddress Class
Home ] Up ] Network Communication Protocols ] Host Names & IP Addresses ] Domains ] Transport Protocols ] Ports ] [ The InetAddress Class ]

 

 

The InetAddress class encapsulates Internet addresses. It supports both host names and IP addresses.

InetAddress is a somewhat unusual class, because it has no public constructors. To get an instance of InetAddress, you use one of the static methods in the class.

To learn about the details of the InetAddress class, click here.

InetAddress Example

Here's an example program that uses the InetAddress class to perform a lookup on a specified host.

package networking;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 *   Application to perform a lookup on the specified host.
 */
public class NodeLookup
{
  /**
   * Main entry point
   * @param args the command line arguments
   *             args[0] contains the hostname to look up
   */
  public static void main(String[] args)
  {
    if (args.length < 1)
    {
      System.err.println("Usage: java networking.NodeLookup <hostname>");
    }
    else
    {
      try
      {
        InetAddress host = InetAddress.getByName(args[0]);
        System.out.println("Host name : " + host.getHostName());
        System.out.println("IP address: " + host.getHostAddress());
      }
      catch (UnknownHostException e)
      {
        System.out.println("Unknown host");
      }
    }
  }
}

If you ask it to look up the host www.rivier.edu, it will output:

Host name : www.rivier.edu
IP address: 66.251.112.2

If you ask it to look up localhost, it will output:

Host name : localhost
IP address: 127.0.0.1

If you ask it to look up 127.0.0.1, it will output the same as for localhost:

Host name : localhost
IP address: 127.0.0.1
The page was last updated February 19, 2008