1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.net.examples.ntp;
19
20 import java.io.IOException;
21 import java.net.InetAddress;
22 import java.time.Duration;
23
24 import org.apache.commons.net.time.TimeTCPClient;
25 import org.apache.commons.net.time.TimeUDPClient;
26
27
28
29
30
31
32
33
34
35 public final class TimeClient {
36
37 public static void main(final String[] args) {
38
39 if (args.length == 1) {
40 try {
41 timeTCP(args[0]);
42 } catch (final IOException e) {
43 e.printStackTrace();
44 System.exit(1);
45 }
46 } else if (args.length == 2 && args[0].equals("-udp")) {
47 try {
48 timeUDP(args[1]);
49 } catch (final IOException e) {
50 e.printStackTrace();
51 System.exit(1);
52 }
53 } else {
54 System.err.println("Usage: TimeClient [-udp] <hostname>");
55 System.exit(1);
56 }
57
58 }
59
60 public static void timeTCP(final String host) throws IOException {
61 final TimeTCPClient client = new TimeTCPClient();
62 try {
63
64 client.setDefaultTimeout(60000);
65 client.connect(host);
66 System.out.println(client.getDate());
67 } finally {
68 client.disconnect();
69 }
70 }
71
72 public static void timeUDP(final String host) throws IOException {
73 final TimeUDPClient client = new TimeUDPClient();
74
75
76 client.setDefaultTimeout(Duration.ofSeconds(60));
77 client.open();
78 System.out.println(client.getDate(InetAddress.getByName(host)));
79 client.close();
80 }
81
82 }