blob: 3e21e2dbdaa9d4aea9ce4ad72869a027c3bdd1c7 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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) {
Nick Kralevich2ed20f82010-12-13 14:32:17 -080075 DatagramSocket socket = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 try {
Nick Kralevich2ed20f82010-12-13 14:32:17 -080077 socket = new DatagramSocket();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 socket.setSoTimeout(timeout);
79 InetAddress address = InetAddress.getByName(host);
80 byte[] buffer = new byte[NTP_PACKET_SIZE];
81 DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);
82
Robert Greenwaltbf7de392010-04-21 17:09:38 -070083 // set mode = 3 (client) and version = 3
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 // mode is in low 3 bits of first byte
85 // version is in bits 3-5 of first byte
86 buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
87
88 // get current time and write it to the request packet
89 long requestTime = System.currentTimeMillis();
90 long requestTicks = SystemClock.elapsedRealtime();
91 writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
92
93 socket.send(request);
Robert Greenwaltbf7de392010-04-21 17:09:38 -070094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 // read the response
96 DatagramPacket response = new DatagramPacket(buffer, buffer.length);
97 socket.receive(response);
98 long responseTicks = SystemClock.elapsedRealtime();
99 long responseTime = requestTime + (responseTicks - requestTicks);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
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);
Robert Greenwalt499a1212010-04-15 12:31:55 -0700106 // 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;
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700115 // if (Config.LOGD) Log.d(TAG, "round trip: " + roundTripTime + " ms");
116 // if (Config.LOGD) Log.d(TAG, "clock offset: " + clockOffset + " ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
Robert Greenwalt499a1212010-04-15 12:31:55 -0700118 // 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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 mRoundTripTime = roundTripTime;
123 } catch (Exception e) {
124 if (Config.LOGD) Log.d(TAG, "request time failed: " + e);
125 return false;
Nick Kralevich2ed20f82010-12-13 14:32:17 -0800126 } finally {
127 if (socket != null) {
128 socket.close();
129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 }
131
132 return true;
133 }
134
135 /**
136 * Returns the time computed from the NTP transaction.
137 *
138 * @return time value computed from NTP server response.
139 */
140 public long getNtpTime() {
141 return mNtpTime;
142 }
143
144 /**
145 * Returns the reference clock value (value of SystemClock.elapsedRealtime())
146 * corresponding to the NTP time.
147 *
148 * @return reference clock corresponding to the NTP time.
149 */
150 public long getNtpTimeReference() {
151 return mNtpTimeReference;
152 }
153
154 /**
155 * Returns the round trip time of the NTP transaction
156 *
157 * @return round trip time in milliseconds.
158 */
159 public long getRoundTripTime() {
160 return mRoundTripTime;
161 }
162
163 /**
164 * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
165 */
166 private long read32(byte[] buffer, int offset) {
167 byte b0 = buffer[offset];
168 byte b1 = buffer[offset+1];
169 byte b2 = buffer[offset+2];
170 byte b3 = buffer[offset+3];
171
172 // convert signed bytes to unsigned values
173 int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
174 int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
175 int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
176 int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
177
178 return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
179 }
180
181 /**
182 * Reads the NTP time stamp at the given offset in the buffer and returns
183 * it as a system time (milliseconds since January 1, 1970).
184 */
185 private long readTimeStamp(byte[] buffer, int offset) {
186 long seconds = read32(buffer, offset);
187 long fraction = read32(buffer, offset + 4);
188 return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
189 }
190
191 /**
192 * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
193 * at the given offset in the buffer.
194 */
195 private void writeTimeStamp(byte[] buffer, int offset, long time) {
196 long seconds = time / 1000L;
197 long milliseconds = time - seconds * 1000L;
198 seconds += OFFSET_1900_TO_1970;
199
200 // write seconds in big endian format
201 buffer[offset++] = (byte)(seconds >> 24);
202 buffer[offset++] = (byte)(seconds >> 16);
203 buffer[offset++] = (byte)(seconds >> 8);
204 buffer[offset++] = (byte)(seconds >> 0);
205
206 long fraction = milliseconds * 0x100000000L / 1000L;
207 // write fraction in big endian format
208 buffer[offset++] = (byte)(fraction >> 24);
209 buffer[offset++] = (byte)(fraction >> 16);
210 buffer[offset++] = (byte)(fraction >> 8);
211 // low order bits should be random data
212 buffer[offset++] = (byte)(Math.random() * 255.0);
213 }
214}