View Javadoc
1   package examples.ntp;
2   /*
3    * Licensed to the Apache Software Foundation (ASF) under one or more
4    * contributor license agreements.  See the NOTICE file distributed with
5    * this work for additional information regarding copyright ownership.
6    * The ASF licenses this file to You under the Apache License, Version 2.0
7    * (the "License"); you may not use this file except in compliance with
8    * the License.  You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  
20  import java.io.IOException;
21  import java.net.InetAddress;
22  import java.net.SocketException;
23  import java.net.UnknownHostException;
24  import java.text.NumberFormat;
25  
26  import org.apache.commons.net.ntp.NTPUDPClient;
27  import org.apache.commons.net.ntp.NtpUtils;
28  import org.apache.commons.net.ntp.NtpV3Packet;
29  import org.apache.commons.net.ntp.TimeInfo;
30  import org.apache.commons.net.ntp.TimeStamp;
31  
32  /***
33   * This is an example program demonstrating how to use the NTPUDPClient
34   * class. This program sends a Datagram client request packet to a
35   * Network time Protocol (NTP) service port on a specified server,
36   * retrieves the time, and prints it to standard output along with
37   * the fields from the NTP message header (e.g. stratum level, reference id,
38   * poll interval, root delay, mode, ...)
39   * See <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc868.txt"> the spec </A>
40   * for details.
41   * <p>
42   * Usage: NTPClient <hostname-or-address-list>
43   * <br>
44   * Example: NTPClient clock.psu.edu
45   *
46   ***/
47  public final class NTPClient
48  {
49  
50      private static final NumberFormat numberFormat = new java.text.DecimalFormat("0.00");
51  
52      /**
53       * Process <code>TimeInfo</code> object and print its details.
54       * @param info <code>TimeInfo</code> object.
55       */
56      public static void processResponse(TimeInfo info)
57      {
58          NtpV3Packet message = info.getMessage();
59          int stratum = message.getStratum();
60          String refType;
61          if (stratum <= 0) {
62              refType = "(Unspecified or Unavailable)";
63          } else if (stratum == 1) {
64              refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc.
65          } else {
66              refType = "(Secondary Reference; e.g. via NTP or SNTP)";
67          }
68          // stratum should be 0..15...
69          System.out.println(" Stratum: " + stratum + " " + refType);
70          int version = message.getVersion();
71          int li = message.getLeapIndicator();
72          System.out.println(" leap=" + li + ", version="
73                  + version + ", precision=" + message.getPrecision());
74  
75          System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")");
76          int poll = message.getPoll();
77          // poll value typically btwn MINPOLL (4) and MAXPOLL (14)
78          System.out.println(" poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll))
79                  + " seconds" + " (2 ** " + poll + ")");
80          double disp = message.getRootDispersionInMillisDouble();
81          System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble())
82                  + ", rootdispersion(ms): " + numberFormat.format(disp));
83  
84          int refId = message.getReferenceId();
85          String refAddr = NtpUtils.getHostAddress(refId);
86          String refName = null;
87          if (refId != 0) {
88              if (refAddr.equals("127.127.1.0")) {
89                  refName = "LOCAL"; // This is the ref address for the Local Clock
90              } else if (stratum >= 2) {
91                  // If reference id has 127.127 prefix then it uses its own reference clock
92                  // defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 mode 5
93                  // for GENERIC DCF77 AM; see refclock.htm from the NTP software distribution.
94                  if (!refAddr.startsWith("127.127")) {
95                      try {
96                          InetAddress addr = InetAddress.getByName(refAddr);
97                          String name = addr.getHostName();
98                          if (name != null && !name.equals(refAddr)) {
99                              refName = name;
100                         }
101                     } catch (UnknownHostException e) {
102                         // some stratum-2 servers sync to ref clock device but fudge stratum level higher... (e.g. 2)
103                         // ref not valid host maybe it's a reference clock name?
104                         // otherwise just show the ref IP address.
105                         refName = NtpUtils.getReferenceClock(message);
106                     }
107                 }
108             } else if (version >= 3 && (stratum == 0 || stratum == 1)) {
109                 refName = NtpUtils.getReferenceClock(message);
110                 // refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.)
111             }
112             // otherwise give up on naming the beast...
113         }
114         if (refName != null && refName.length() > 1) {
115             refAddr += " (" + refName + ")";
116         }
117         System.out.println(" Reference Identifier:\t" + refAddr);
118 
119         TimeStamp refNtpTime = message.getReferenceTimeStamp();
120         System.out.println(" Reference Timestamp:\t" + refNtpTime + "  " + refNtpTime.toDateString());
121 
122         // Originate Time is time request sent by client (t1)
123         TimeStamp origNtpTime = message.getOriginateTimeStamp();
124         System.out.println(" Originate Timestamp:\t" + origNtpTime + "  " + origNtpTime.toDateString());
125 
126         long destTime = info.getReturnTime();
127         // Receive Time is time request received by server (t2)
128         TimeStamp rcvNtpTime = message.getReceiveTimeStamp();
129         System.out.println(" Receive Timestamp:\t" + rcvNtpTime + "  " + rcvNtpTime.toDateString());
130 
131         // Transmit time is time reply sent by server (t3)
132         TimeStamp xmitNtpTime = message.getTransmitTimeStamp();
133         System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + "  " + xmitNtpTime.toDateString());
134 
135         // Destination time is time reply received by client (t4)
136         TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);
137         System.out.println(" Destination Timestamp:\t" + destNtpTime + "  " + destNtpTime.toDateString());
138 
139         info.computeDetails(); // compute offset/delay if not already done
140         Long offsetValue = info.getOffset();
141         Long delayValue = info.getDelay();
142         String delay = (delayValue == null) ? "N/A" : delayValue.toString();
143         String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();
144 
145         System.out.println(" Roundtrip delay(ms)=" + delay
146                 + ", clock offset(ms)=" + offset); // offset in ms
147     }
148 
149     public static void main(String[] args)
150     {
151         if (args.length == 0) {
152             System.err.println("Usage: NTPClient <hostname-or-address-list>");
153             System.exit(1);
154         }
155 
156         NTPUDPClient client = new NTPUDPClient();
157         // We want to timeout if a response takes longer than 10 seconds
158         client.setDefaultTimeout(10000);
159         try {
160             client.open();
161             for (String arg : args)
162             {
163                 System.out.println();
164                 try {
165                     InetAddress hostAddr = InetAddress.getByName(arg);
166                     System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
167                     TimeInfo info = client.getTime(hostAddr);
168                     processResponse(info);
169                 } catch (IOException ioe) {
170                     ioe.printStackTrace();
171                 }
172             }
173         } catch (SocketException e) {
174             e.printStackTrace();
175         }
176 
177         client.close();
178     }
179 
180 }