InetAddressTest.java

Sometimes need the address of the local host. If you simply ask for the address of localhost, you always get the local loopback address 127.0.0.1, which cannot be used by others to connect to your computer.

C:\Users\John\v2ch04\inetAddress>java InetAddressTest localhost
localhost/127.0.0.1
localhost/0:0:0:0:0:0:0:1
Instead, use the static getLocalHost method to get the address of your local host:
C:\Users\John\v2ch04\inetAddress>java InetAddressTest
DESKTOP-OC5P358/192.168.1.74

Arguments: C:\Users\John\v2ch04\inetAddress>java InetAddressTest www.mcgrawhill.com www.mcgrawhill.com/23.221.12.80


InetAddressTest.java

import java.io.*;
import java.net.*;

/**
 * This program demonstrates the InetAddress class. Supply a host name as command-line argument, or
 * run without command-line arguments to see the address of the local host.
 * @version 1.02 2012-06-05
 * @author Cay Horstmann
 */
public class InetAddressTest
{
   public static void main(String[] args) throws IOException
   {
      if (args.length > 0)
      {
         String host = args[0];
         InetAddress[] addresses = InetAddress.getAllByName(host);
         for (InetAddress a : addresses)
            System.out.println(a);
      }
      else
      {
         InetAddress localHostAddress = InetAddress.getLocalHost();
         System.out.println(localHostAddress);
      }
   }
}


Maintained by John Loomis, updated Wed Apr 12 13:27:11 2017