001 package examples.ntp;
002
003 /*
004 * Copyright 2001-2005 The Apache Software Foundation
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019 import java.io.IOException;
020 import java.net.InetAddress;
021 import org.apache.commons.net.TimeTCPClient;
022 import org.apache.commons.net.TimeUDPClient;
023
024 /***
025 * This is an example program demonstrating how to use the TimeTCPClient
026 * and TimeUDPClient classes.
027 * This program connects to the default time service port of a
028 * specified server, retrieves the time, and prints it to standard output.
029 * See <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc868.txt"> the spec </A>
030 * for details. The default is to use the TCP port. Use the -udp flag to
031 * use the UDP port.
032 * <p>
033 * Usage: TimeClient [-udp] <hostname>
034 * <p>
035 ***/
036 public final class TimeClient
037 {
038
039 public static final void timeTCP(String host) throws IOException
040 {
041 TimeTCPClient client = new TimeTCPClient();
042 try {
043 // We want to timeout if a response takes longer than 60 seconds
044 client.setDefaultTimeout(60000);
045 client.connect(host);
046 System.out.println(client.getDate());
047 } finally {
048 client.disconnect();
049 }
050 }
051
052 public static final void timeUDP(String host) throws IOException
053 {
054 TimeUDPClient client = new TimeUDPClient();
055
056 // We want to timeout if a response takes longer than 60 seconds
057 client.setDefaultTimeout(60000);
058 client.open();
059 System.out.println(client.getDate(InetAddress.getByName(host)));
060 client.close();
061 }
062
063 public static final void main(String[] args)
064 {
065
066 if (args.length == 1)
067 {
068 try
069 {
070 timeTCP(args[0]);
071 }
072 catch (IOException e)
073 {
074 e.printStackTrace();
075 System.exit(1);
076 }
077 }
078 else if (args.length == 2 && args[0].equals("-udp"))
079 {
080 try
081 {
082 timeUDP(args[1]);
083 }
084 catch (IOException e)
085 {
086 e.printStackTrace();
087 System.exit(1);
088 }
089 }
090 else
091 {
092 System.err.println("Usage: TimeClient [-udp] <hostname>");
093 System.exit(1);
094 }
095
096 }
097
098 }
099