Skip to content

Commit 3b510ad

Browse files
author
Anna Aitchison
committed
Add code for understanding-Java workshop
1 parent 9296396 commit 3b510ad

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

‎understanding-java/.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/DnsResolver.class
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import java.net.InetAddress;
2+
import java.net.UnknownHostException;
3+
4+
class DnsResolver {
5+
public static void main(String[] args) {
6+
if (args.length != 1) {
7+
System.err.printf("Expected exactly one argument, but got %d%n", args.length);
8+
System.exit(1);
9+
}
10+
String host = args[0];
11+
12+
String[] parts = host.split("\\.");
13+
System.out.printf("The top-level domain of the host %s is %s%n", host, parts[parts.length - 1]);
14+
15+
try {
16+
InetAddress[] ipAddresses = InetAddress.getAllByName(host);
17+
if (ipAddresses.length == 0) {
18+
System.out.printf("The host %s did not resolve to any IP addresses%n", host);
19+
} else {
20+
String pluralSuffix = ipAddresses.length == 1 ? "" : "es";
21+
System.out.printf("The host %s resolved to the following IP address%s:%n", host, pluralSuffix);
22+
}
23+
for (InetAddress ipAddress : ipAddresses) {
24+
System.out.println(ipAddress.getHostAddress());
25+
}
26+
} catch (UnknownHostException e) {
27+
System.err.printf("Failed to resolve %s: %s%n", host, e.getMessage());
28+
System.exit(1);
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)