|
| 1 | +/* |
| 2 | + * ntp-client |
| 3 | + * https://github.com/moonpyk/node-ntp |
| 4 | + * |
| 5 | + * Copyright (c) 2013 Clément Bourgeois |
| 6 | + * Licensed under the MIT license. |
| 7 | + */ |
| 8 | + |
| 9 | +(function (exports) { |
| 10 | + "use strict"; |
| 11 | + |
| 12 | + var dgram = require('dgram'); |
| 13 | + |
| 14 | + exports.defaultNtpPort = 123; |
| 15 | + exports.defaultNtpServer = "pool.ntp.org"; |
| 16 | + |
| 17 | + /** |
| 18 | + * @param {string} server IP/Hostname of the remote NTP Server |
| 19 | + * @param {number} port Remote NTP Server port number |
| 20 | + * @param {function(Object, Date)} callback |
| 21 | + */ |
| 22 | + exports.getNetworkTime = function (server, port, callback) { |
| 23 | + var client = dgram.createSocket("udp4"), |
| 24 | + ntpData = new Buffer(48); |
| 25 | + |
| 26 | + ntpData[0] = 0x1B; // RFC 2030 |
| 27 | + |
| 28 | + for (var i = 1; i < 48; i++) { |
| 29 | + ntpData[i] = 0; |
| 30 | + } |
| 31 | + |
| 32 | + client.send(ntpData, 0, ntpData.length, port, server, function (err) { |
| 33 | + if (err) { |
| 34 | + callback(err, null); |
| 35 | + client.close(); |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + client.on('message', function (msg) { |
| 40 | + client.close(); |
| 41 | + |
| 42 | + // Offset to get to the "Transmit Timestamp" field (time at which the reply |
| 43 | + // departed the server for the client, in 64-bit timestamp format." |
| 44 | + var offsetTransmitTime = 40, |
| 45 | + intpart = 0, |
| 46 | + fractpart = 0; |
| 47 | + |
| 48 | + // Get the seconds part |
| 49 | + for (var i = 0; i <= 3; i++) { |
| 50 | + intpart = 256 * intpart + msg[offsetTransmitTime + i]; |
| 51 | + } |
| 52 | + |
| 53 | + // Get the seconds fraction |
| 54 | + for (i = 4; i <= 7; i++) { |
| 55 | + fractpart = 256 * fractpart + msg[offsetTransmitTime + i]; |
| 56 | + } |
| 57 | + |
| 58 | + var milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000); |
| 59 | + |
| 60 | + // **UTC** time |
| 61 | + var date = new Date("Jan 01 1900 GMT"); |
| 62 | + date.setUTCMilliseconds(date.getUTCMilliseconds() + milliseconds); |
| 63 | + |
| 64 | + callback(err, date); |
| 65 | + }); |
| 66 | + }); |
| 67 | + }; |
| 68 | + |
| 69 | + exports.demo = function (argv) { |
| 70 | + exports.getNetworkTime( |
| 71 | + exports.defaultNtpServer, |
| 72 | + exports.defaultNtpPort, |
| 73 | + function (err, date) { |
| 74 | + if (err) { |
| 75 | + console.error(err); |
| 76 | + return; |
| 77 | + } |
| 78 | + |
| 79 | + console.log(date); |
| 80 | + }); |
| 81 | + }; |
| 82 | +}(exports)); |
0 commit comments