Skip to content

Instantly share code, notes, and snippets.

@dsc
Created October 12, 2012 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsc/3881509 to your computer and use it in GitHub Desktop.
Save dsc/3881509 to your computer and use it in GitHub Desktop.
Listens for UDP packets, sending the stream to stdout and also teeing it to another port on the local machine.
#!/usr/bin/env node
// Listens for UDP packets, sending the stream to stdout and
// also teeing it to another port on the local machine.
//
// Usage: teegram.js LISTEN_PORT TEE_PORT
var dgram = require('dgram');
var DEBUG = false
, LISTEN_PORT = parseInt(process.argv[1])
, TEE_PORT = parseInt(process.argv[2])
;
if (!(LISTEN_PORT > 0 && TEE_PORT > 0)) {
console.error("Usage: teegram.js LISTEN_PORT TEE_PORT");
console.error(" Invalid port(s): LISTEN_PORT="+LISTEN_PORT+"; TEE_PORT="+TEE_PORT);
process.exit(1);
}
var server = dgram.createSocket("udp4")
, client = dgram.createSocket("udp4")
;
server.on("message", function(msg, rinfo){
DEBUG && console.error([
new Date(),
rinfo.address + ":" + rinfo.port,
String(msg)
].join('\t'));
// Log to stdout
console.log(String(msg));
// Tee to TEE_PORT
client.send(msg, 0, msg.length, TEE_PORT, 'localhost', function(err, bytes){
err && DEBUG && console.error(err);
});
});
DEBUG && server.on("listening", function(){
var adr = server.address();
console.error("Starting UDP Server! (" + adr.address + ":" + adr.port + ")");
});
server.bind(LISTEN_PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment