1 package examples.ntp;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 import java.io.IOException;
22 import java.net.InetAddress;
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
36
37
38
39 public final class TimeClient
40 {
41
42 public static final void timeTCP(String host) throws IOException
43 {
44 TimeTCPClient client = new TimeTCPClient();
45 try {
46
47 client.setDefaultTimeout(60000);
48 client.connect(host);
49 System.out.println(client.getDate());
50 } finally {
51 client.disconnect();
52 }
53 }
54
55 public static final void timeUDP(String host) throws IOException
56 {
57 TimeUDPClient client = new TimeUDPClient();
58
59
60 client.setDefaultTimeout(60000);
61 client.open();
62 System.out.println(client.getDate(InetAddress.getByName(host)));
63 client.close();
64 }
65
66 public static final void main(String[] args)
67 {
68
69 if (args.length == 1)
70 {
71 try
72 {
73 timeTCP(args[0]);
74 }
75 catch (IOException e)
76 {
77 e.printStackTrace();
78 System.exit(1);
79 }
80 }
81 else if (args.length == 2 && args[0].equals("-udp"))
82 {
83 try
84 {
85 timeUDP(args[1]);
86 }
87 catch (IOException e)
88 {
89 e.printStackTrace();
90 System.exit(1);
91 }
92 }
93 else
94 {
95 System.err.println("Usage: TimeClient [-udp] <hostname>");
96 System.exit(1);
97 }
98
99 }
100
101 }
102