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