modified DNSqueries.java, added loop and some comment
[staff/wgh1/DNSqueries.git] / DNSqueries.java
1 /*
2 * (c) 2010-2013 WGH1@BFH
3 *
4 * demo program to show the use of the java hostname resolver
5 *
6 */
7
8 // import the Scanner class
9 import java.util.Scanner;
10 // import the InetAddress class
11 import java.net.InetAddress;
12 // import the UnknownHostException class
13 import java.net.UnknownHostException;
14
15 public class DNSqueries {
16
17 public static void main(String[] args) {
18
19 // do not cache DNS responses inside java
20 java.security.Security.setProperty("networkaddress.cache.ttl" , "0");
21 java.security.Security.setProperty("networkaddress.cache.negative.ttl" , "0");
22
23 // iteration variable
24 int i;
25 // input scanner
26 Scanner s;
27 // internet address
28 InetAddress iAddr;
29 // array of internet addresses
30 InetAddress[] iList;
31 // hostnames
32 String inHostName, canHostName;
33
34 // new scanner
35 s = new Scanner(System.in);
36
37 // loop until "exit"
38 do {
39 // catch exceptions
40 try {
41 // read in hostname or IP address
42 System.out.print("\nEnter Hostname or IP-Address (exit to quit): ");
43 inHostName = s.next();
44
45 // exit if "hostname" is "exit"
46 if (inHostName.equals("exit")) {
47 System.out.println("\nGood Bye!\n");
48 break;
49 }
50
51 // determines the IP address of a host, given the host's name
52 iAddr = InetAddress.getByName( inHostName );
53
54 // gets the fully qualified domain name for this IP address
55 canHostName = iAddr.getCanonicalHostName();
56
57 // given the name of a host, returns an array of its IP addresses,
58 // based on the configured name services on the system
59 iList = InetAddress.getAllByName( canHostName );
60
61 // print out the FQDN
62 System.out.println("\nCanonical Hostname: " + iAddr.getCanonicalHostName() + "\n");
63
64 // print out ..
65 for (i=0;i<iList.length;i++) {
66 // .. FQDN ..
67 System.out.println("Hostname " + i + ": " + iList[i].getCanonicalHostName() +
68 // .. and address
69 " Address " + i + ": " + iList[i].getHostAddress() );
70 }
71 }
72 // exception handler
73 // handle unknown host exception
74 catch (UnknownHostException exception) {
75 System.err.println("\nHost unknown: " + exception.getMessage() + "\n");
76 }
77 } while (true); // loop ..
78 }
79 }