    001package org.apache.commons.net.ntp;
    002/*
    003 * Licensed to the Apache Software Foundation (ASF) under one or more
    004 * contributor license agreements.  See the NOTICE file distributed with
    005 * this work for additional information regarding copyright ownership.
    006 * The ASF licenses this file to You under the Apache License, Version 2.0
    007 * (the "License"); you may not use this file except in compliance with
    008 * the License.  You may obtain a copy of the License at
    009 *
    010 *      http://www.apache.org/licenses/LICENSE-2.0
    011 *
    012 * Unless required by applicable law or agreed to in writing, software
    013 * distributed under the License is distributed on an "AS IS" BASIS,
    014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    015 * See the License for the specific language governing permissions and
    016 * limitations under the License.
    017 */
    018
    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
    028 * Network Time Protocol (NTP) described in RFC 1305 as well as the
    029 * Simple Network Time Protocol (SNTP) in RFC-2030. To use the class,
    030 * merely open a local datagram socket with <a href="#open"> open </a>
    031 * and call <a href="#getTime"> getTime </a> to retrieve the time. Then call
    032 * <a href="org.apache.commons.net.DatagramSocketClient.html#close"> close </a>
    033 * to close the connection properly.
    034 * Successive calls to <a href="#getTime"> getTime </a> are permitted
    035 * without re-establishing a connection.  That is because UDP is a
    036 * connectionless protocol and the Network Time Protocol is stateless.
    037 *
    038 ***/
    039
    040public final class NTPUDPClient extends DatagramSocketClient
    041{
    042    /*** The default NTP port.  It is set to 123 according to RFC 1305. ***/
    043    public static final int DEFAULT_PORT = 123;
    044
    045    private int version = NtpV3Packet.VERSION_3;
    046
    047    /***
    048     * Retrieves the time information from the specified server and port and
    049     * returns it. The time is the number of miliiseconds since
    050     * 00:00 (midnight) 1 January 1900 UTC, as specified by RFC 1305.
    051     * This method reads the raw NTP packet and constructs a <i>TimeInfo</i>
    052     * object that allows access to all the fields of the NTP message header.
    053     * <p>
    054     * @param host The address of the server.
    055     * @param port The port of the service.
    056     * @return The time value retrieved from the server.
    057     * @throws IOException If an error occurs while retrieving the time.
    058     ***/
    059    public TimeInfo getTime(final InetAddress host, final int port) throws IOException
    060    {
    061        // if not connected then open to next available UDP port
    062        if (!isOpen())
    063        {
    064            open();
    065        }
    066
    067        final NtpV3Packet message = new NtpV3Impl();
    068        message.setMode(NtpV3Packet.MODE_CLIENT);
    069        message.setVersion(version);
    070        final DatagramPacket sendPacket = message.getDatagramPacket();
    071        sendPacket.setAddress(host);
    072        sendPacket.setPort(port);
    073
    074        final NtpV3Packet recMessage = new NtpV3Impl();
    075        final DatagramPacket receivePacket = recMessage.getDatagramPacket();
    076
    077        /*
    078         * Must minimize the time between getting the current time,
    079         * timestamping the packet, and sending it out which
    080         * introduces an error in the delay time.
    081         * No extraneous logging and initializations here !!!
    082         */
    083        final TimeStamp now = TimeStamp.getCurrentTime();
    084
    085        // Note that if you do not set the transmit time field then originating time
    086        // in server response is all 0's which is "Thu Feb 07 01:28:16 EST 2036".
    087        message.setTransmitTime(now);
    088
    089        _socket_.send(sendPacket);
    090        _socket_.receive(receivePacket);
    091
    092        final long returnTime = System.currentTimeMillis();
    093        // create TimeInfo message container but don't pre-compute the details yet
    094        final TimeInfo info = new TimeInfo(recMessage, returnTime, false);
    095
    096        return info;
    097    }
    098
    099    /***
    100     * Retrieves the time information from the specified server on the
    101     * default NTP port and returns it. The time is the number of miliiseconds
    102     * since 00:00 (midnight) 1 January 1900 UTC, as specified by RFC 1305.
    103     * This method reads the raw NTP packet and constructs a <i>TimeInfo</i>
    104     * object that allows access to all the fields of the NTP message header.
    105     * <p>
    106     * @param host The address of the server.
    107     * @return The time value retrieved from the server.
    108     * @throws IOException If an error occurs while retrieving the time.
    109     ***/
    110    public TimeInfo getTime(final InetAddress host) throws IOException
    111    {
    112        return getTime(host, NtpV3Packet.NTP_PORT);
    113    }
    114
    115    /***
    116     * Returns the NTP protocol version number that client sets on request packet
    117     * that is sent to remote host (e.g. 3=NTP v3, 4=NTP v4, etc.)
    118     *
    119     * @return  the NTP protocol version number that client sets on request packet.
    120     * @see #setVersion(int)
    121     ***/
    122    public int getVersion()
    123    {
    124        return version;
    125    }
    126
    127    /***
    128     * Sets the NTP protocol version number that client sets on request packet
    129     * communicate with remote host.
    130     *
    131     * @param version the NTP protocol version number
    132     ***/
    133    public void setVersion(final int version)
    134    {
    135        this.version = version;
    136    }
    137
    138}