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; 022import java.time.Duration; 023 024import org.apache.commons.net.time.TimeTCPClient; 025import org.apache.commons.net.time.TimeUDPClient; 026 027/** 028 * 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 029 * 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 030 * 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). 031 * <p> 032 * Usage: rdate [-udp] <hostname> 033 */ 034public final class rdate { 035 036 public static void main(final String[] args) { 037 038 if (args.length == 1) { 039 try { 040 timeTCP(args[0]); 041 } catch (final IOException e) { 042 e.printStackTrace(); 043 System.exit(1); 044 } 045 } else if (args.length == 2 && args[0].equals("-udp")) { 046 try { 047 timeUDP(args[1]); 048 } catch (final IOException e) { 049 e.printStackTrace(); 050 System.exit(1); 051 } 052 } else { 053 System.err.println("Usage: rdate [-udp] <hostname>"); 054 System.exit(1); 055 } 056 057 } 058 059 public static void timeTCP(final String host) throws IOException { 060 final TimeTCPClient client = new TimeTCPClient(); 061 062 // We want to timeout if a response takes longer than 60 seconds 063 client.setDefaultTimeout(60000); 064 client.connect(host); 065 System.out.println(client.getDate().toString()); 066 client.disconnect(); 067 } 068 069 public static void timeUDP(final String host) throws IOException { 070 try (TimeUDPClient client = new TimeUDPClient()) { 071 // We want to timeout if a response takes longer than 60 seconds 072 client.setDefaultTimeout(Duration.ofSeconds(60)); 073 client.open(); 074 System.out.println(client.getDate(InetAddress.getByName(host)).toString()); 075 } 076 } 077 078}