-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathntp.js
90 lines (72 loc) · 2.87 KB
/
ntp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* ntp-client
* https://github.com/moonpyk/node-ntp-client
*
* Copyright (c) 2013 Clément Bourgeois
* Licensed under the MIT license.
*/
(function (exports) {
"use strict";
var dgram = require('dgram');
exports.defaultNtpPort = 123;
exports.defaultNtpServer = "pool.ntp.org";
/**
* Amount of acceptable time to await for a response from the remote server.
* Configured default to 100ms.
*/
exports.ntpReplyTimeout = 100;
/**
* Fetches the current NTP Time from the given server and port.
* @param {string} server IP/Hostname of the remote NTP Server
* @param {number} port Remote NTP Server port number
* @param {function(Object, Date)} callback(err, date) Async callback for
* the result date or eventually error.
*/
exports.getNetworkTime = function (server, port, callback) {
if (callback === null || typeof callback !== "function") {
return;
}
server = server || exports.defaultNtpServer;
port = port || exports.defaultNtpPort;
var client = dgram.createSocket("udp4"),
ntpData = new Buffer(48);
// RFC 2030 -> LI = 0 (no warning, 2 bits), VN = 3 (IPv4 only, 3 bits), Mode = 3 (Client Mode, 3 bits) -> 1 byte
// -> rtol(LI, 6) ^ rotl(VN, 3) ^ rotl(Mode, 0)
// -> = 0x00 ^ 0x18 ^ 0x03
ntpData[0] = 0x1B;
for (var i = 1; i < 48; i++) {
ntpData[i] = 0;
}
var timeout = setTimeout(function () {
client.close();
}, exports.ntpReplyTimeout);
client.send(ntpData, 0, ntpData.length, port, server, function (err) {
if (err) {
client.close();
return;
}
client.on('message', function (msg, sender) {
// Offset to get to the "Transmit Timestamp" field (time at which the reply
// departed the server for the client, in 64-bit timestamp format."
var offsetTransmitTime = 40,
offsetStratum = 1,
intpart = 0,
fractpart = 0;
var stratum = msg[offsetStratum];
// Get the seconds part
for (var i = 0; i <= 3; i++) {
intpart = 256 * intpart + msg[offsetTransmitTime + i];
}
// Get the seconds fraction
for (i = 4; i <= 7; i++) {
fractpart = 256 * fractpart + msg[offsetTransmitTime + i];
}
var milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000);
// **UTC** time
var date = new Date("Jan 01 1900 GMT");
date.setUTCMilliseconds(date.getUTCMilliseconds() + milliseconds);
callback(sender.address, stratum, date);
});
});
};
}(exports));