NTP forwarder in Node.js

This code creates two UDP sockets:

a server socket to listen for incoming NTP requests, and a client socket to send NTP requests to an NTP server (pool.ntp.org).

When the server socket receives an NTP request, it sends the same request to the NTP server via the client socket. When the client socket receives a response, it sends the response back to the original requester via the server socket.

This way, the forwarder acts as a middleman between the requester and the NTP server.

const dgram = require('dgram');
const server = dgram.createSocket('udp4');
const client = dgram.createSocket('udp4');

server.on('message', (msg, rinfo) => {
  client.send(msg, 0, msg.length, 123, 'pool.ntp.org', (err) => {
    if (err) {
      console.error(err);
    }
  });
});

server.bind(123, () => {
  console.log(`NTP forwarder started on port 123`);
});

client.once('message', (msg) => {
  server.send(msg, 0, msg.length, rinfo.port, rinfo.address, (err) => {
    if (err) {
      console.error(err);
    }
  });
});

Read More

I hope this post was helpful to you.

Leave a reaction if you liked this post!