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.daytime.DaytimeTCPClient; 025import org.apache.commons.net.daytime.DaytimeUDPClient; 026 027/** 028 * This is an example program demonstrating how to use the DaytimeTCP and DaytimeUDP classes. This program connects to the default daytime service port of a 029 * specified server, retrieves the daytime, and prints it to standard output. The default is to use the TCP port. Use the -udp flag to use the UDP port. 030 * <p> 031 * Usage: daytime [-udp] <hostname> 032 */ 033public final class daytime { 034 035 public static void daytimeTCP(final String host) throws IOException { 036 final DaytimeTCPClient client = new DaytimeTCPClient(); 037 038 // We want to timeout if a response takes longer than 60 seconds 039 client.setDefaultTimeout(60000); 040 client.connect(host); 041 System.out.println(client.getTime().trim()); 042 client.disconnect(); 043 } 044 045 public static void daytimeUDP(final String host) throws IOException { 046 try (DaytimeUDPClient client = new DaytimeUDPClient()) { 047 048 // We want to timeout if a response takes longer than 60 seconds 049 client.setDefaultTimeout(Duration.ofSeconds(60)); 050 client.open(); 051 System.out.println(client.getTime(InetAddress.getByName(host)).trim()); 052 } 053 } 054 055 public static void main(final String[] args) { 056 057 if (args.length == 1) { 058 try { 059 daytimeTCP(args[0]); 060 } catch (final IOException e) { 061 e.printStackTrace(); 062 System.exit(1); 063 } 064 } else if (args.length == 2 && args[0].equals("-udp")) { 065 try { 066 daytimeUDP(args[1]); 067 } catch (final IOException e) { 068 e.printStackTrace(); 069 System.exit(1); 070 } 071 } else { 072 System.err.println("Usage: daytime [-udp] <hostname>"); 073 System.exit(1); 074 } 075 076 } 077 078}