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.net.SocketException; 023import java.net.UnknownHostException; 024import java.text.NumberFormat; 025import java.time.Duration; 026 027import org.apache.commons.net.ntp.NTPUDPClient; 028import org.apache.commons.net.ntp.NtpUtils; 029import org.apache.commons.net.ntp.NtpV3Packet; 030import org.apache.commons.net.ntp.TimeInfo; 031import org.apache.commons.net.ntp.TimeStamp; 032 033/** 034 * This is an example program demonstrating how to use the NTPUDPClient class. This program sends a Datagram client request packet to a Network time Protocol 035 * (NTP) service port on a specified server, retrieves the time, and prints it to standard output along with the fields from the NTP message header (e.g. 036 * stratum level, reference id, poll interval, root delay, mode, ...) See <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc868.txt"> the spec </A> for details. 037 * <p> 038 * Usage: NTPClient <hostname-or-address-list> 039 * </p> 040 * <p> 041 * Example: NTPClient clock.psu.edu 042 * </p> 043 */ 044public final class NTPClient { 045 046 private static final NumberFormat numberFormat = new java.text.DecimalFormat("0.00"); 047 048 public static void main(final String[] args) { 049 if (args.length == 0) { 050 System.err.println("Usage: NTPClient <hostname-or-address-list>"); 051 System.exit(1); 052 } 053 054 final NTPUDPClient client = new NTPUDPClient(); 055 // We want to timeout if a response takes longer than 10 seconds 056 client.setDefaultTimeout(Duration.ofSeconds(10)); 057 try { 058 client.open(); 059 for (final String arg : args) { 060 System.out.println(); 061 try { 062 final InetAddress hostAddr = InetAddress.getByName(arg); 063 System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress()); 064 final TimeInfo info = client.getTime(hostAddr); 065 processResponse(info); 066 } catch (final IOException ioe) { 067 ioe.printStackTrace(); 068 } 069 } 070 } catch (final SocketException e) { 071 e.printStackTrace(); 072 } 073 074 client.close(); 075 } 076 077 /** 078 * Process <code>TimeInfo</code> object and print its details. 079 * 080 * @param info <code>TimeInfo</code> object. 081 */ 082 public static void processResponse(final TimeInfo info) { 083 final NtpV3Packet message = info.getMessage(); 084 final int stratum = message.getStratum(); 085 final String refType; 086 if (stratum <= 0) { 087 refType = "(Unspecified or Unavailable)"; 088 } else if (stratum == 1) { 089 refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc. 090 } else { 091 refType = "(Secondary Reference; e.g. via NTP or SNTP)"; 092 } 093 // stratum should be 0..15... 094 System.out.println(" Stratum: " + stratum + " " + refType); 095 final int version = message.getVersion(); 096 final int li = message.getLeapIndicator(); 097 System.out.println(" leap=" + li + ", version=" + version + ", precision=" + message.getPrecision()); 098 099 System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")"); 100 final int poll = message.getPoll(); 101 // poll value typically btwn MINPOLL (4) and MAXPOLL (14) 102 System.out.println(" poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " seconds" + " (2 ** " + poll + ")"); 103 final double disp = message.getRootDispersionInMillisDouble(); 104 System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble()) + ", rootdispersion(ms): " + numberFormat.format(disp)); 105 106 final int refId = message.getReferenceId(); 107 String refAddr = NtpUtils.getHostAddress(refId); 108 String refName = null; 109 if (refId != 0) { 110 if (refAddr.equals("127.127.1.0")) { 111 refName = "LOCAL"; // This is the ref address for the Local Clock 112 } else if (stratum >= 2) { 113 // If reference id has 127.127 prefix then it uses its own reference clock 114 // defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 mode 5 115 // for GENERIC DCF77 AM; see refclock.htm from the NTP software distribution. 116 if (!refAddr.startsWith("127.127")) { 117 try { 118 final InetAddress addr = InetAddress.getByName(refAddr); 119 final String name = addr.getHostName(); 120 if (name != null && !name.equals(refAddr)) { 121 refName = name; 122 } 123 } catch (final UnknownHostException e) { 124 // some stratum-2 servers sync to ref clock device but fudge stratum level higher... (e.g. 2) 125 // ref not valid host maybe it's a reference clock name? 126 // otherwise just show the ref IP address. 127 refName = NtpUtils.getReferenceClock(message); 128 } 129 } 130 } else if (version >= 3 && (stratum == 0 || stratum == 1)) { 131 refName = NtpUtils.getReferenceClock(message); 132 // refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.) 133 } 134 // otherwise give up on naming the beast... 135 } 136 if (refName != null && refName.length() > 1) { 137 refAddr += " (" + refName + ")"; 138 } 139 System.out.println(" Reference Identifier:\t" + refAddr); 140 141 final TimeStamp refNtpTime = message.getReferenceTimeStamp(); 142 System.out.println(" Reference Timestamp:\t" + refNtpTime + " " + refNtpTime.toDateString()); 143 144 // Originate Time is time request sent by client (t1) 145 final TimeStamp origNtpTime = message.getOriginateTimeStamp(); 146 System.out.println(" Originate Timestamp:\t" + origNtpTime + " " + origNtpTime.toDateString()); 147 148 final long destTimeMillis = info.getReturnTime(); 149 // Receive Time is time request received by server (t2) 150 final TimeStamp rcvNtpTime = message.getReceiveTimeStamp(); 151 System.out.println(" Receive Timestamp:\t" + rcvNtpTime + " " + rcvNtpTime.toDateString()); 152 153 // Transmit time is time reply sent by server (t3) 154 final TimeStamp xmitNtpTime = message.getTransmitTimeStamp(); 155 System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + " " + xmitNtpTime.toDateString()); 156 157 // Destination time is time reply received by client (t4) 158 final TimeStamp destNtpTime = TimeStamp.getNtpTime(destTimeMillis); 159 System.out.println(" Destination Timestamp:\t" + destNtpTime + " " + destNtpTime.toDateString()); 160 161 info.computeDetails(); // compute offset/delay if not already done 162 final Long offsetMillis = info.getOffset(); 163 final Long delayMillis = info.getDelay(); 164 final String delay = delayMillis == null ? "N/A" : delayMillis.toString(); 165 final String offset = offsetMillis == null ? "N/A" : offsetMillis.toString(); 166 167 System.out.println(" Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset); // offset in ms 168 } 169 170}