    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 *      https://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.ntp;
    019
    020import java.io.IOException;
    021import java.net.DatagramPacket;
    022import java.net.InetAddress;
    023
    024import org.apache.commons.net.DatagramSocketClient;
    025
    026/**
    027 * 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
    028 * 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>
    029 * to retrieve the time. Then call <a href="org.apache.commons.net.DatagramSocketClient.html#close"> close </a> to close the connection properly. Successive
    030 * calls to <a href="#getTime"> getTime </a> are permitted without re-establishing a connection. That is because UDP is a connectionless protocol and the
    031 * Network Time Protocol is stateless.
    032 */
    033public final class NTPUDPClient extends DatagramSocketClient {
    034
    035    /** The default NTP port. It is set to 123 according to RFC 1305. */
    036    public static final int DEFAULT_PORT = 123;
    037
    038    private int version = NtpV3Packet.VERSION_3;
    039
    040    /**
    041     * Constructs a new instance.
    042     */
    043    public NTPUDPClient() {
    044        // empty
    045    }
    046
    047    /**
    048     * Gets 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
    049     * (midnight) 1 January 1900 UTC, as specified by RFC 1305. This method reads the raw NTP packet and constructs a <em>TimeInfo</em> object that allows
    050     * access to all the fields of the NTP message header.
    051     *
    052     * @param host The address of the server.
    053     * @return The time value retrieved from the server.
    054     * @throws IOException If an error occurs while retrieving the time.
    055     */
    056    public TimeInfo getTime(final InetAddress host) throws IOException {
    057        return getTime(host, NtpV3Packet.NTP_PORT);
    058    }
    059
    060    /**
    061     * Gets 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
    062     * 1900 UTC, as specified by RFC 1305. This method reads the raw NTP packet and constructs a <em>TimeInfo</em> object that allows access to all the fields
    063     * of the NTP message header.
    064     *
    065     * @param host The address of the server.
    066     * @param port The port of the service.
    067     * @return The time value retrieved from the server.
    068     * @throws IOException If an error occurs while retrieving the time or if received packet does not match the request.
    069     */
    070    public TimeInfo getTime(final InetAddress host, final int port) throws IOException {
    071        // if not connected then open to next available UDP port
    072        if (!isOpen()) {
    073            open();
    074        }
    075
    076        final NtpV3Packet message = new NtpV3Impl();
    077        message.setMode(NtpV3Packet.MODE_CLIENT);
    078        message.setVersion(version);
    079        final DatagramPacket sendPacket = message.getDatagramPacket();
    080        sendPacket.setAddress(host);
    081        sendPacket.setPort(port);
    082
    083        final NtpV3Packet recMessage = new NtpV3Impl();
    084        final DatagramPacket receivePacket = recMessage.getDatagramPacket();
    085
    086        /*
    087         * 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
    088         * extraneous logging and initializations here !!!
    089         */
    090        final TimeStamp now = TimeStamp.getCurrentTime();
    091
    092        // Note that if you do not set the transmit time field then originating time
    093        // in server response is all 0's which is "Thu Feb 07 01:28:16 EST 2036".
    094        message.setTransmitTime(now);
    095
    096        checkOpen().send(sendPacket);
    097        checkOpen().receive(receivePacket);
    098
    099        final long returnTimeMillis = System.currentTimeMillis();
    100
    101        // Prevent invalid time information if response does not match request
    102        if (!now.equals(recMessage.getOriginateTimeStamp())) {
    103            throw new IOException("Originate time does not match the request");
    104        }
    105
    106        // create TimeInfo message container but don't pre-compute the details yet
    107        return new TimeInfo(recMessage, returnTimeMillis, false);
    108    }
    109
    110    /**
    111     * Gets 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.)
    112     *
    113     * @return the NTP protocol version number that client sets on request packet.
    114     * @see #setVersion(int)
    115     */
    116    public int getVersion() {
    117        return version;
    118    }
    119
    120    /**
    121     * Sets the NTP protocol version number that client sets on request packet communicate with remote host.
    122     *
    123     * @param version the NTP protocol version number
    124     */
    125    public void setVersion(final int version) {
    126        this.version = version;
    127    }
    128
    129}