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