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; 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. This program connects to the default time service port of a 028 * 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 029 * details. The default is to use the TCP port. Use the -udp flag to use the UDP port. 030 * <p> 031 * Usage: TimeClient [-udp] <hostname> 032 * </p> 033 */ 034public final class TimeClient { 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: TimeClient [-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 try { 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()); 066 } finally { 067 client.disconnect(); 068 } 069 } 070 071 public static void timeUDP(final String host) throws IOException { 072 final TimeUDPClient client = new TimeUDPClient(); 073 074 // We want to timeout if a response takes longer than 60 seconds 075 client.setDefaultTimeout(60000); 076 client.open(); 077 System.out.println(client.getDate(InetAddress.getByName(host))); 078 client.close(); 079 } 080 081}