Home | History | Annotate | Download | only in net
      1 /*
      2  * Copyright (C) 2008 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.net;
     18 
     19 import android.os.SystemClock;
     20 import android.util.Config;
     21 import android.util.Log;
     22 
     23 import java.io.IOException;
     24 import java.net.DatagramPacket;
     25 import java.net.DatagramSocket;
     26 import java.net.InetAddress;
     27 
     28 /**
     29  * {@hide}
     30  *
     31  * Simple SNTP client class for retrieving network time.
     32  *
     33  * Sample usage:
     34  * <pre>SntpClient client = new SntpClient();
     35  * if (client.requestTime("time.foo.com")) {
     36  *     long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
     37  * }
     38  * </pre>
     39  */
     40 public class SntpClient
     41 {
     42     private static final String TAG = "SntpClient";
     43 
     44     private static final int REFERENCE_TIME_OFFSET = 16;
     45     private static final int ORIGINATE_TIME_OFFSET = 24;
     46     private static final int RECEIVE_TIME_OFFSET = 32;
     47     private static final int TRANSMIT_TIME_OFFSET = 40;
     48     private static final int NTP_PACKET_SIZE = 48;
     49 
     50     private static final int NTP_PORT = 123;
     51     private static final int NTP_MODE_CLIENT = 3;
     52     private static final int NTP_VERSION = 3;
     53 
     54     // Number of seconds between Jan 1, 1900 and Jan 1, 1970
     55     // 70 years plus 17 leap days
     56     private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
     57 
     58     // system time computed from NTP server response
     59     private long mNtpTime;
     60 
     61     // value of SystemClock.elapsedRealtime() corresponding to mNtpTime
     62     private long mNtpTimeReference;
     63 
     64     // round trip time in milliseconds
     65     private long mRoundTripTime;
     66 
     67     /**
     68      * Sends an SNTP request to the given host and processes the response.
     69      *
     70      * @param host host name of the server.
     71      * @param timeout network timeout in milliseconds.
     72      * @return true if the transaction was successful.
     73      */
     74     public boolean requestTime(String host, int timeout) {
     75         try {
     76             DatagramSocket socket = new DatagramSocket();
     77             socket.setSoTimeout(timeout);
     78             InetAddress address = InetAddress.getByName(host);
     79             byte[] buffer = new byte[NTP_PACKET_SIZE];
     80             DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);
     81 
     82             // set mode = 3 (client) and version = 3
     83             // mode is in low 3 bits of first byte
     84             // version is in bits 3-5 of first byte
     85             buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
     86 
     87             // get current time and write it to the request packet
     88             long requestTime = System.currentTimeMillis();
     89             long requestTicks = SystemClock.elapsedRealtime();
     90             writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
     91 
     92             socket.send(request);
     93 
     94             // read the response
     95             DatagramPacket response = new DatagramPacket(buffer, buffer.length);
     96             socket.receive(response);
     97             long responseTicks = SystemClock.elapsedRealtime();
     98             long responseTime = requestTime + (responseTicks - requestTicks);
     99             socket.close();
    100 
    101             // extract the results
    102             long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
    103             long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
    104             long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
    105             long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
    106             // receiveTime = originateTime + transit + skew
    107             // responseTime = transmitTime + transit - skew
    108             // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
    109             //             = ((originateTime + transit + skew - originateTime) +
    110             //                (transmitTime - (transmitTime + transit - skew)))/2
    111             //             = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
    112             //             = (transit + skew - transit + skew)/2
    113             //             = (2 * skew)/2 = skew
    114             long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2;
    115             // if (Config.LOGD) Log.d(TAG, "round trip: " + roundTripTime + " ms");
    116             // if (Config.LOGD) Log.d(TAG, "clock offset: " + clockOffset + " ms");
    117 
    118             // save our results - use the times on this side of the network latency
    119             // (response rather than request time)
    120             mNtpTime = responseTime + clockOffset;
    121             mNtpTimeReference = responseTicks;
    122             mRoundTripTime = roundTripTime;
    123         } catch (Exception e) {
    124             if (Config.LOGD) Log.d(TAG, "request time failed: " + e);
    125             return false;
    126         }
    127 
    128         return true;
    129     }
    130 
    131     /**
    132      * Returns the time computed from the NTP transaction.
    133      *
    134      * @return time value computed from NTP server response.
    135      */
    136     public long getNtpTime() {
    137         return mNtpTime;
    138     }
    139 
    140     /**
    141      * Returns the reference clock value (value of SystemClock.elapsedRealtime())
    142      * corresponding to the NTP time.
    143      *
    144      * @return reference clock corresponding to the NTP time.
    145      */
    146     public long getNtpTimeReference() {
    147         return mNtpTimeReference;
    148     }
    149 
    150     /**
    151      * Returns the round trip time of the NTP transaction
    152      *
    153      * @return round trip time in milliseconds.
    154      */
    155     public long getRoundTripTime() {
    156         return mRoundTripTime;
    157     }
    158 
    159     /**
    160      * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
    161      */
    162     private long read32(byte[] buffer, int offset) {
    163         byte b0 = buffer[offset];
    164         byte b1 = buffer[offset+1];
    165         byte b2 = buffer[offset+2];
    166         byte b3 = buffer[offset+3];
    167 
    168         // convert signed bytes to unsigned values
    169         int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
    170         int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
    171         int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
    172         int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
    173 
    174         return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
    175     }
    176 
    177     /**
    178      * Reads the NTP time stamp at the given offset in the buffer and returns
    179      * it as a system time (milliseconds since January 1, 1970).
    180      */
    181     private long readTimeStamp(byte[] buffer, int offset) {
    182         long seconds = read32(buffer, offset);
    183         long fraction = read32(buffer, offset + 4);
    184         return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
    185     }
    186 
    187     /**
    188      * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
    189      * at the given offset in the buffer.
    190      */
    191     private void writeTimeStamp(byte[] buffer, int offset, long time) {
    192         long seconds = time / 1000L;
    193         long milliseconds = time - seconds * 1000L;
    194         seconds += OFFSET_1900_TO_1970;
    195 
    196         // write seconds in big endian format
    197         buffer[offset++] = (byte)(seconds >> 24);
    198         buffer[offset++] = (byte)(seconds >> 16);
    199         buffer[offset++] = (byte)(seconds >> 8);
    200         buffer[offset++] = (byte)(seconds >> 0);
    201 
    202         long fraction = milliseconds * 0x100000000L / 1000L;
    203         // write fraction in big endian format
    204         buffer[offset++] = (byte)(fraction >> 24);
    205         buffer[offset++] = (byte)(fraction >> 16);
    206         buffer[offset++] = (byte)(fraction >> 8);
    207         // low order bits should be random data
    208         buffer[offset++] = (byte)(Math.random() * 255.0);
    209     }
    210 }
    211