01: /*
02: * Copyright 2001-2005 The Apache Software Foundation
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package examples;
17:
18: import java.io.IOException;
19: import java.net.InetAddress;
20: import org.apache.commons.net.TimeTCPClient;
21: import org.apache.commons.net.TimeUDPClient;
22:
23: /***
24: * This is an example program demonstrating how to use the TimeTCPClient
25: * and TimeUDPClient classes. It's very similar to the simple Unix rdate
26: * command. This program connects to the default time service port of a
27: * specified server, retrieves the time, and prints it to standard output.
28: * The default is to use the TCP port. Use the -udp flag to use the UDP
29: * port. You can test this program by using the NIST time server at
30: * 132.163.135.130 (warning: the IP address may change).
31: * <p>
32: * Usage: rdate [-udp] <hostname>
33: * <p>
34: * <p>
35: * @author Daniel F. Savarese
36: ***/
37: public final class rdate {
38:
39: public static final void timeTCP(String host) throws IOException {
40: TimeTCPClient client = new TimeTCPClient();
41:
42: // We want to timeout if a response takes longer than 60 seconds
43: client.setDefaultTimeout(60000);
44: client.connect(host);
45: System.out.println(client.getDate().toString());
46: client.disconnect();
47: }
48:
49: public static final void timeUDP(String host) throws IOException {
50: TimeUDPClient client = new TimeUDPClient();
51:
52: // We want to timeout if a response takes longer than 60 seconds
53: client.setDefaultTimeout(60000);
54: client.open();
55: System.out.println(client.getDate(InetAddress.getByName(host))
56: .toString());
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: rdate [-udp] <hostname>");
78: System.exit(1);
79: }
80:
81: }
82:
83: }
|