Simple SNTP client class for retrieving network time.
Sample usage:
SntpClient client = new SntpClient();
if (client.requestTime("time.foo.com")) {
long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
}
private static final String TAG = "SntpClient";
private static final int NTP_PORT = 123;
Sends an SNTP request to the given host and processes the response.
- Parameters:
host host name of the server.timeout network timeout in milliseconds.- Returns:
- true if the transaction was successful.
long responseTime = requestTime + (responseTicks - requestTicks);
long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2;
if (false) Log.d(TAG, "request time failed: " + e);
Returns the time computed from the NTP transaction.
- Returns:
- time value computed from NTP server response.
Returns the reference clock value (value of SystemClock.elapsedRealtime())
corresponding to the NTP time.
- Returns:
- reference clock corresponding to the NTP time.
Returns the round trip time of the NTP transaction
- Returns:
- round trip time in milliseconds.
Reads an unsigned 32 bit big endian number from the given offset in the buffer.
private long read32(byte[] buffer, int offset) { byte b0 = buffer[offset];
byte b1 = buffer[offset+1];
byte b2 = buffer[offset+2];
byte b3 = buffer[offset+3];
int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
Reads the NTP time stamp at the given offset in the buffer and returns
it as a system time (milliseconds since January 1, 1970).
long seconds = read32(buffer, offset);
long fraction = read32(buffer, offset + 4);
Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
at the given offset in the buffer.
long seconds = time / 1000L;
long milliseconds = time - seconds * 1000L;
buffer[offset++] = (byte)(seconds >> 24);
buffer[offset++] = (byte)(seconds >> 16);
buffer[offset++] = (byte)(seconds >> 8);
buffer[offset++] = (byte)(seconds >> 0);
long fraction = milliseconds * 0x100000000L / 1000L;
buffer[offset++] = (byte)(fraction >> 24);
buffer[offset++] = (byte)(fraction >> 16);
buffer[offset++] = (byte)(fraction >> 8);
buffer[offset++] = (byte)(Math.random() * 255.0);