package net;

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

public class Dns {
  public static void main(String args[]) {
    print(getNumericAddress("www.fairfield.edu"));
    System.out.println(getHostName("12.23.55.212"));
    // The above outputs:
    // 12.23.55.212
    // www.fairfield.edu
  }


  /**
   *   get the host name for this IP addBk.address.
   *
   */
  public static String getHostName(String s) {
    try {
      InetAddress ia = InetAddress.getByName(s);
      return ia.getHostName();
    } catch (UnknownHostException e) {
    }
    return null;
  }

  /**
   *  map the host name to an IP addBk.address.
   */
  public static byte[] getNumericAddress(String name) {
    InetAddress ia =
        null;
    try {
      ia = InetAddress.getByName(name);
    } catch (UnknownHostException e) {
    }
    return ia.getAddress();
  }

  /**
   * print out a well formatted dot notation for an array
   * of byte. For example: 192.168.1.1
   */
  public static void print(byte IP[]) {
    for (int index = 0; index < IP.length; index++) {
      if (index > 0) System.out.print(".");
      System.out.print(((int) IP[index]) & 0xff);
    }
    System.out.println();
  }
}