1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.net.ntp;
19
20 import java.io.IOException;
21 import java.net.DatagramPacket;
22 import java.net.InetAddress;
23
24 import org.apache.commons.net.DatagramSocketClient;
25
26 /**
27 * The NTPUDPClient class is a UDP implementation of a client for the Network Time Protocol (NTP) described in RFC 1305 as well as the Simple Network Time
28 * Protocol (SNTP) in RFC-2030. To use the class, merely open a local datagram socket with <a href="#open"> open </a> and call <a href="#getTime"> getTime </a>
29 * to retrieve the time. Then call <a href="org.apache.commons.net.DatagramSocketClient.html#close"> close </a> to close the connection properly. Successive
30 * calls to <a href="#getTime"> getTime </a> are permitted without re-establishing a connection. That is because UDP is a connectionless protocol and the
31 * Network Time Protocol is stateless.
32 */
33 public final class NTPUDPClient extends DatagramSocketClient {
34 /** The default NTP port. It is set to 123 according to RFC 1305. */
35 public static final int DEFAULT_PORT = 123;
36
37 private int version = NtpV3Packet.VERSION_3;
38
39 /**
40 * Retrieves the time information from the specified server on the default NTP port and returns it. The time is the number of milliseconds since 00:00
41 * (midnight) 1 January 1900 UTC, as specified by RFC 1305. This method reads the raw NTP packet and constructs a <i>TimeInfo</i> object that allows access
42 * to all the fields of the NTP message header.
43 *
44 * @param host The address of the server.
45 * @return The time value retrieved from the server.
46 * @throws IOException If an error occurs while retrieving the time.
47 */
48 public TimeInfo getTime(final InetAddress host) throws IOException {
49 return getTime(host, NtpV3Packet.NTP_PORT);
50 }
51
52 /**
53 * Retrieves the time information from the specified server and port and returns it. The time is the number of milliseconds since 00:00 (midnight) 1 January
54 * 1900 UTC, as specified by RFC 1305. This method reads the raw NTP packet and constructs a <i>TimeInfo</i> object that allows access to all the fields of
55 * the NTP message header.
56 *
57 * @param host The address of the server.
58 * @param port The port of the service.
59 * @return The time value retrieved from the server.
60 * @throws IOException If an error occurs while retrieving the time or if received packet does not match the request.
61 */
62 public TimeInfo getTime(final InetAddress host, final int port) throws IOException {
63 // if not connected then open to next available UDP port
64 if (!isOpen()) {
65 open();
66 }
67
68 final NtpV3Packet message = new NtpV3Impl();
69 message.setMode(NtpV3Packet.MODE_CLIENT);
70 message.setVersion(version);
71 final DatagramPacket sendPacket = message.getDatagramPacket();
72 sendPacket.setAddress(host);
73 sendPacket.setPort(port);
74
75 final NtpV3Packet recMessage = new NtpV3Impl();
76 final DatagramPacket receivePacket = recMessage.getDatagramPacket();
77
78 /*
79 * Must minimize the time between getting the current time, timestamping the packet, and sending it out which introduces an error in the delay time. No
80 * extraneous logging and initializations here !!!
81 */
82 final TimeStamp now = TimeStamp.getCurrentTime();
83
84 // Note that if you do not set the transmit time field then originating time
85 // in server response is all 0's which is "Thu Feb 07 01:28:16 EST 2036".
86 message.setTransmitTime(now);
87
88 checkOpen().send(sendPacket);
89 checkOpen().receive(receivePacket);
90
91 final long returnTimeMillis = System.currentTimeMillis();
92
93 // Prevent invalid time information if response does not match request
94 if (!now.equals(recMessage.getOriginateTimeStamp())) {
95 throw new IOException("Originate time does not match the request");
96 }
97
98 // create TimeInfo message container but don't pre-compute the details yet
99 return new TimeInfo(recMessage, returnTimeMillis, false);
100 }
101
102 /**
103 * Returns the NTP protocol version number that client sets on request packet that is sent to remote host (e.g. 3=NTP v3, 4=NTP v4, etc.)
104 *
105 * @return the NTP protocol version number that client sets on request packet.
106 * @see #setVersion(int)
107 */
108 public int getVersion() {
109 return version;
110 }
111
112 /**
113 * Sets the NTP protocol version number that client sets on request packet communicate with remote host.
114 *
115 * @param version the NTP protocol version number
116 */
117 public void setVersion(final int version) {
118 this.version = version;
119 }
120
121 }