Last active
February 1, 2017 05:19
-
-
Save kevincennis/7307d41dc113f51c7711a50104c37e44 to your computer and use it in GitHub Desktop.
ntp client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const dgram = require('dgram'); | |
const socket = dgram.createSocket('udp4'); | |
const port = 123; | |
const host = 'pool.ntp.org'; | |
const data = Buffer.alloc( 48 ); | |
// RFC 2030 header stuff... | |
// this all gets packed into a single byte that looks like this: | |
// | |
// 0 1 2 3 4 5 6 7 | |
// +-+-+-+-+-+-+-+-+ | |
// |LI | VN |Mode | | |
// +-+-+-+-+-+-+-+-+ | |
// Leap indicator – no warning = 0 (2 bits, shift 6) | |
const LI = 0 << 6; | |
// Version Number – IPV4-only = 3 (3 bits, shift 3) | |
const VN = 3 << 3; | |
// Mode – client = 3 (3 bits, shift 0) | |
const MODE = 3 << 0; | |
// bitwise OR each value to get 0b00011011, or 27 | |
const HEADER = LI | VN | MODE; | |
// all we need here is the first byte, everything else is zeroed out... | |
data.writeUInt8( HEADER, 0 ); | |
socket.on( 'message', msg => { | |
// integer ms since Jan 1 1900 | |
const ms = msg.readUInt32BE( 40 ) * 1000; | |
// fractional ms in addition to above | |
const fraction = msg.readUInt32BE( 44 ) * 1000 / Math.pow( 2, 32 ); | |
const time = ms + fraction; | |
const date = new Date('Jan 01 1900 GMT'); | |
date.setUTCMilliseconds( time ); | |
console.log( date ); | |
socket.close(); | |
}); | |
socket.send( data, port, host ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment