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 org.apache.commons.net.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 and TimeUDPClient classes. It's very similar to the simple Unix rdate command. This 028 * program connects to the default time service port of a specified server, retrieves the time, and prints it to standard output. The default is to use the TCP 029 * port. Use the -udp flag to use the UDP port. You can test this program by using the NIST time server at 132.163.135.130 (warning: the IP address may change). 030 * <p> 031 * Usage: rdate [-udp] <hostname> 032 */ 033public final class rdate { 034 035 public static void main(final String[] args) { 036 037 if (args.length == 1) { 038 try { 039 timeTCP(args[0]); 040 } catch (final IOException e) { 041 e.printStackTrace(); 042 System.exit(1); 043 } 044 } else if (args.length == 2 && args[0].equals("-udp")) { 045 try { 046 timeUDP(args[1]); 047 } catch (final IOException e) { 048 e.printStackTrace(); 049 System.exit(1); 050 } 051 } else { 052 System.err.println("Usage: rdate [-udp] <hostname>"); 053 System.exit(1); 054 } 055 056 } 057 058 public static void timeTCP(final String host) throws IOException { 059 final TimeTCPClient client = new TimeTCPClient(); 060 061 // We want to timeout if a response takes longer than 60 seconds 062 client.setDefaultTimeout(60000); 063 client.connect(host); 064 System.out.println(client.getDate().toString()); 065 client.disconnect(); 066 } 067 068 public static void timeUDP(final String host) throws IOException { 069 final TimeUDPClient client = new TimeUDPClient(); 070 071 // We want to timeout if a response takes longer than 60 seconds 072 client.setDefaultTimeout(60000); 073 client.open(); 074 System.out.println(client.getDate(InetAddress.getByName(host)).toString()); 075 client.close(); 076 } 077 078}