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.ntp; 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. This program connects to the default time service port of a 029 * specified server, retrieves the time, and prints it to standard output. See <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc868.txt"> the spec </A> for 030 * details. The default is to use the TCP port. Use the -udp flag to use the UDP port. 031 * <p> 032 * Usage: TimeClient [-udp] <hostname> 033 * </p> 034 */ 035public final class TimeClient { 036 037 public static void main(final String[] args) { 038 039 if (args.length == 1) { 040 try { 041 timeTCP(args[0]); 042 } catch (final IOException e) { 043 e.printStackTrace(); 044 System.exit(1); 045 } 046 } else if (args.length == 2 && args[0].equals("-udp")) { 047 try { 048 timeUDP(args[1]); 049 } catch (final IOException e) { 050 e.printStackTrace(); 051 System.exit(1); 052 } 053 } else { 054 System.err.println("Usage: TimeClient [-udp] <hostname>"); 055 System.exit(1); 056 } 057 058 } 059 060 public static void timeTCP(final String host) throws IOException { 061 final TimeTCPClient client = new TimeTCPClient(); 062 try { 063 // We want to timeout if a response takes longer than 60 seconds 064 client.setDefaultTimeout(60000); 065 client.connect(host); 066 System.out.println(client.getDate()); 067 } finally { 068 client.disconnect(); 069 } 070 } 071 072 public static void timeUDP(final String host) throws IOException { 073 final TimeUDPClient client = new TimeUDPClient(); 074 075 // We want to timeout if a response takes longer than 60 seconds 076 client.setDefaultTimeout(Duration.ofSeconds(60)); 077 client.open(); 078 System.out.println(client.getDate(InetAddress.getByName(host))); 079 client.close(); 080 } 081 082}