Last active
January 8, 2024 02:54
Star
You must be signed in to star a gist
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
'use strict'; | |
const process = require('process'); | |
const dgram = require('dgram'); | |
// Command line args: | |
let [listenport, fwdport, fwdaddr, mindelay, maxdelay] = process.argv.slice(2); | |
// It will listen on <listenport> and act as a reverse proxy for the UDP service | |
// at <fwdaddr>:<fwdport>. All packets will be delayed by a uniformly | |
// distributed random value between <mindelay> and <maxdelay> in milleseconds. | |
// Defaults: | |
listenport = Number(listenport) || 30001; | |
fwdport = Number(fwdport) || 30000; | |
fwdaddr = fwdaddr || '127.0.0.1'; | |
mindelay = Number(mindelay) || 400; | |
maxdelay = Number(maxdelay) || (mindelay * 1.25); | |
console.log(`${listenport}->${fwdaddr}:${fwdport} min ${mindelay} max ${maxdelay}`); | |
function delaysend(sock, msg, toport, toaddr, fromport, fromaddr) { | |
const delay = Math.floor(Math.random() * (maxdelay - mindelay) + mindelay); | |
setTimeout(() => sock.send(msg, toport, toaddr), delay); | |
} | |
const server = dgram.createSocket('udp4'); | |
server.on('error', e => { throw e; }); | |
server.on('listening', () => `listening on ${listenport}`); | |
server.bind(listenport); | |
const fwds = {}; | |
server.on('message', (msg, info) => { | |
const { address, port } = info; | |
const key = `${address}:${port}`; | |
let sock = fwds[key]; | |
if(!sock) { | |
fwds[key] = sock = dgram.createSocket('udp4'); | |
sock.on('error', e => { throw e; }); | |
server.on('listening', () => console.log(`new connection from ${address}:${port | |
} relaying via port ${sock.address().port}`)); | |
sock.on('message', m => delaysend(server, m, port, address, fwdport, fwdaddr)); | |
} | |
delaysend(sock, msg, fwdport, fwdaddr, port, address); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment