SntpClient.java revision 54b6cfa9a9e5b861a9930af873580d6dc20f773c
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 17package android.net; 18 19import android.os.SystemClock; 20import android.util.Config; 21import android.util.Log; 22 23import java.io.IOException; 24import java.net.DatagramPacket; 25import java.net.DatagramSocket; 26import 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 */ 40public 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 long clockOffset = (receiveTime - originateTime) + (transmitTime - responseTime); 107 if (Config.LOGD) Log.d(TAG, "round trip: " + roundTripTime + " ms"); 108 if (Config.LOGD) Log.d(TAG, "clock offset: " + clockOffset + " ms"); 109 110 // save our results 111 mNtpTime = requestTime + clockOffset; 112 mNtpTimeReference = requestTicks; 113 mRoundTripTime = roundTripTime; 114 } catch (Exception e) { 115 if (Config.LOGD) Log.d(TAG, "request time failed: " + e); 116 return false; 117 } 118 119 return true; 120 } 121 122 /** 123 * Returns the time computed from the NTP transaction. 124 * 125 * @return time value computed from NTP server response. 126 */ 127 public long getNtpTime() { 128 return mNtpTime; 129 } 130 131 /** 132 * Returns the reference clock value (value of SystemClock.elapsedRealtime()) 133 * corresponding to the NTP time. 134 * 135 * @return reference clock corresponding to the NTP time. 136 */ 137 public long getNtpTimeReference() { 138 return mNtpTimeReference; 139 } 140 141 /** 142 * Returns the round trip time of the NTP transaction 143 * 144 * @return round trip time in milliseconds. 145 */ 146 public long getRoundTripTime() { 147 return mRoundTripTime; 148 } 149 150 /** 151 * Reads an unsigned 32 bit big endian number from the given offset in the buffer. 152 */ 153 private long read32(byte[] buffer, int offset) { 154 byte b0 = buffer[offset]; 155 byte b1 = buffer[offset+1]; 156 byte b2 = buffer[offset+2]; 157 byte b3 = buffer[offset+3]; 158 159 // convert signed bytes to unsigned values 160 int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0); 161 int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1); 162 int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2); 163 int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3); 164 165 return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3; 166 } 167 168 /** 169 * Reads the NTP time stamp at the given offset in the buffer and returns 170 * it as a system time (milliseconds since January 1, 1970). 171 */ 172 private long readTimeStamp(byte[] buffer, int offset) { 173 long seconds = read32(buffer, offset); 174 long fraction = read32(buffer, offset + 4); 175 return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L); 176 } 177 178 /** 179 * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp 180 * at the given offset in the buffer. 181 */ 182 private void writeTimeStamp(byte[] buffer, int offset, long time) { 183 long seconds = time / 1000L; 184 long milliseconds = time - seconds * 1000L; 185 seconds += OFFSET_1900_TO_1970; 186 187 // write seconds in big endian format 188 buffer[offset++] = (byte)(seconds >> 24); 189 buffer[offset++] = (byte)(seconds >> 16); 190 buffer[offset++] = (byte)(seconds >> 8); 191 buffer[offset++] = (byte)(seconds >> 0); 192 193 long fraction = milliseconds * 0x100000000L / 1000L; 194 // write fraction in big endian format 195 buffer[offset++] = (byte)(fraction >> 24); 196 buffer[offset++] = (byte)(fraction >> 16); 197 buffer[offset++] = (byte)(fraction >> 8); 198 // low order bits should be random data 199 buffer[offset++] = (byte)(Math.random() * 255.0); 200 } 201} 202