(host: string, timeoutMs = 2500)
| 66 | const packet = Buffer.alloc(48); |
| 67 | // LI = 0 (no warning), VN = 4, Mode = 3 (client) -> 0b00 100 011 = 0x23 |
| 68 | packet[0] = 0x23; |
| 69 | // Transmit timestamp: set to client time (optional but good practice) |
| 70 | const t1ms = Date.now(); |
| 71 | const t1 = toNtpSecondsAndFrac(t1ms); |
| 72 | packet.writeUInt32BE(t1.sec, 40); |
| 73 | packet.writeUInt32BE(t1.frac, 44); |
| 74 | |
| 75 | function cleanup() { |
| 76 | try { |
| 77 | socket.close(); |
| 78 | } catch {} |
| 79 | if (timeoutTimer) clearTimeout(timeoutTimer); |
| 80 | } |
| 81 | |
| 82 | socket.once("error", (err) => { |
| 83 | cleanup(); |
| 84 | reject(err); |
| 85 | }); |
| 86 | |
| 87 | socket.once("message", (msg, rinfo) => { |
| 88 | const t4ms = Date.now(); |
| 89 | try { |
| 90 | // Parse stratum and timestamps |
| 91 | const stratum = msg[1]; |
| 92 | const t2ms = readNtpTimestamp(msg, 32); |
| 93 | const t3ms = readNtpTimestamp(msg, 40); |
| 94 | |
| 95 | let delayMs: number | undefined; |
| 96 | let offsetMs: number | undefined; |
| 97 | let serverTimeMs: number | undefined; |
| 98 | |
| 99 | if (typeof t2ms === "number" && typeof t3ms === "number") { |
| 100 | // Full NTP offset/delay calculation |
| 101 | delayMs = (t4ms - t1ms) - (t3ms - t2ms); |
| 102 | offsetMs = ((t2ms - t1ms) + (t3ms - t4ms)) / 2; |
| 103 | // Best estimate of server time when received = t4 + offset |
| 104 | serverTimeMs = Math.round(t4ms + (offsetMs || 0)); |
| 105 | } else if (typeof t3ms === "number") { |
| 106 | // Fallback: assume symmetric path, use half the RTT |
| 107 | const rtt = t4ms - t1ms; |
| 108 | delayMs = rtt; |
| 109 | offsetMs = t3ms - (t1ms + rtt / 2); |
| 110 | serverTimeMs = Math.round(t4ms + (offsetMs || 0)); |
| 111 | } |
| 112 | |
| 113 | cleanup(); |
| 114 | resolve({ |
| 115 | server: host, |
| 116 | ip: rinfo?.address, |
| 117 | stratum, |
| 118 | delayMs, |
| 119 | offsetMs, |
| 120 | serverTimeMs, |
| 121 | raw: msg, |
| 122 | }); |
| 123 | } catch (e) { |
| 124 | cleanup(); |
| 125 | reject(e); |
no test coverage detected