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 018package examples.unix; 019 020import java.io.IOException; 021import java.net.InetAddress; 022 023import org.apache.commons.net.time.TimeTCPClient; 024import 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 ***/ 037public final class rdate 038{ 039 040 public static final void timeTCP(String host) throws IOException 041 { 042 TimeTCPClient client = new TimeTCPClient(); 043 044 // We want to timeout if a response takes longer than 60 seconds 045 client.setDefaultTimeout(60000); 046 client.connect(host); 047 System.out.println(client.getDate().toString()); 048 client.disconnect(); 049 } 050 051 public static final void timeUDP(String host) throws IOException 052 { 053 TimeUDPClient client = new TimeUDPClient(); 054 055 // We want to timeout if a response takes longer than 60 seconds 056 client.setDefaultTimeout(60000); 057 client.open(); 058 System.out.println(client.getDate(InetAddress.getByName(host)).toString()); 059 client.close(); 060 } 061 062 063 public static 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: rdate [-udp] <hostname>"); 093 System.exit(1); 094 } 095 096 } 097 098} 099