JMU
Using Internet Addresses and the DNS
in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


The Internet Protocol (v4)
The Internet Protocol (v6)
Internet Addresses in Java
The Domain Name System (DNS)
DNS in Java
DNS in Java (cont.)

Finding the Local Address

javaexamples/internet/MyAddress.java
        import java.net.*;

/**
 * A utility for determining a machines IP address
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison University
 *
 */
public class MyAddress
{

    /**
     * The entry point
     *
     * @param args  The command-line arguments
     */
    public static void main(String[] args)
    {
       InetAddress ip;

       System.out.println("\n");
       try 
       {
          ip = InetAddress.getLocalHost();
          System.out.println("Address: "+ip);
       } 
       catch (UnknownHostException uhe)
       {
          System.out.println("This computer's address is unavailable!");
       }

       System.out.println("\n");
    }
}
        
DNS in Java (cont.)

Finding Any Address

javaexamples/internet/GetAddress.java
        import java.net.*;

/**
 * A utility for determining the IP addresses
 * of a host given its name
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison University
 *
 */
public class GetAddress
{

    /**
     * The entry point
     *
     * @param args  The command-line arguments
     */
    public static void main(String[] args)
    {
       InetAddress[]      ip;
       int                i;


       System.out.println("\n");
       if (args.length == 0) 
       {
          System.out.println("You must enter a host name.");
       } 
       else
       {
          try 
          {
             ip = InetAddress.getAllByName(args[0]);

             for (i=0; i < ip.length; i++) 
             {
                System.out.println("Address: "+ip[i]);
             }
          }
          catch (UnknownHostException uhe) 
          {
             System.out.println("This computer's address is unavailable!");
          }
       }
       System.out.println("\n");
    }
}