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