Skip to content

Instantly share code, notes, and snippets.

@shuhei
Created July 30, 2015 12:58
Show Gist options
  • Save shuhei/45140f9bcffd900fe1b1 to your computer and use it in GitHub Desktop.
Save shuhei/45140f9bcffd900fe1b1 to your computer and use it in GitHub Desktop.
Wiretap TCP connection
var net = require('net');
var stream = require('stream');
var util = require('util');
// ANSI colors.
var green = '\u001b[32m';
var yellow = '\u001b[33m';
var reset = '\u001b[0m';
// CLI args.
var host = process.argv[2];
if (!host) {
console.log('usage: node wiretap.js <host> [<port>]');
process.exit(1);
}
var port = parseInt(process.argv[3] || '80', 10);
// A transform stream to tap data.
function WireTap(prefix) {
stream.Transform.call(this, {});
this.prefix = prefix;
}
util.inherits(WireTap, stream.Transform);
WireTap.prototype._transform = function (chunk, encoding, callback) {
console.log(this.prefix + "'" + chunk.toString('utf-8') + "'");
callback(null, chunk);
};
// Server.
var server = net.createServer(function (c) {
var c2t = new WireTap(green + '> ');
var t2c = new WireTap(yellow + '< ');
console.log(reset + '-- client connection started');
var target = net.connect(port, host, function () {
console.log(reset + '-- target connection opened');
c.pipe(c2t).pipe(target);
target.pipe(t2c).pipe(c);
});
target.on('end', function () {
console.log(reset + '-- target connection closed');
unpipe();
});
c.on('end', function () {
console.log(reset + '-- client connection closed');
unpipe();
});
function unpipe() {
c.unpipe(c2t);
c2t.unpipe(target);
target.unpipe(t2c);
t2c.unpipe(c);
}
});
server.listen(5050, function () {
console.log('Listening on 5050, proxying to', host + ':' + port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment