01: package examples.ntp;
02:
03: /*
04: * Copyright 2001-2005 The Apache Software Foundation
05: *
06: * Licensed under the Apache License, Version 2.0 (the "License");
07: * you may not use this file except in compliance with the License.
08: * You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing, software
13: * distributed under the License is distributed on an "AS IS" BASIS,
14: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15: * See the License for the specific language governing permissions and
16: * limitations under the License.
17: */
18:
19: import java.io.IOException;
20: import java.net.InetAddress;
21: import org.apache.commons.net.TimeTCPClient;
22: import org.apache.commons.net.TimeUDPClient;
23:
24: /***
25: * This is an example program demonstrating how to use the TimeTCPClient
26: * and TimeUDPClient classes.
27: * This program connects to the default time service port of a
28: * specified server, retrieves the time, and prints it to standard output.
29: * See <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc868.txt"> the spec </A>
30: * for details. The default is to use the TCP port. Use the -udp flag to
31: * use the UDP port.
32: * <p>
33: * Usage: TimeClient [-udp] <hostname>
34: * <p>
35: ***/
36: public final class TimeClient {
37:
38: public static final void timeTCP(String host) throws IOException {
39: TimeTCPClient client = new TimeTCPClient();
40: try {
41: // We want to timeout if a response takes longer than 60 seconds
42: client.setDefaultTimeout(60000);
43: client.connect(host);
44: System.out.println(client.getDate());
45: } finally {
46: client.disconnect();
47: }
48: }
49:
50: public static final void timeUDP(String host) throws IOException {
51: TimeUDPClient client = new TimeUDPClient();
52:
53: // We want to timeout if a response takes longer than 60 seconds
54: client.setDefaultTimeout(60000);
55: client.open();
56: System.out.println(client.getDate(InetAddress.getByName(host)));
57: client.close();
58: }
59:
60: public static final void main(String[] args) {
61:
62: if (args.length == 1) {
63: try {
64: timeTCP(args[0]);
65: } catch (IOException e) {
66: e.printStackTrace();
67: System.exit(1);
68: }
69: } else if (args.length == 2 && args[0].equals("-udp")) {
70: try {
71: timeUDP(args[1]);
72: } catch (IOException e) {
73: e.printStackTrace();
74: System.exit(1);
75: }
76: } else {
77: System.err.println("Usage: TimeClient [-udp] <hostname>");
78: System.exit(1);
79: }
80:
81: }
82:
83: }
|