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