Skip to content

Instantly share code, notes, and snippets.

@tralamazza
Created July 31, 2011 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tralamazza/1117341 to your computer and use it in GitHub Desktop.
Save tralamazza/1117341 to your computer and use it in GitHub Desktop.
node.js bind() hack
/*
* Author: Daniel Tralamazza <tralamazza@gmail.com>
*
* Patch Socket for a before connect event.
* Important! You must require this module before anything else.
*
* Usage:
*
* var patch = require('./bind_hack');
* var bind_f = process.binding('net').bind;
* patch(function(socket, remote_port) {
* console.log('Socket.fd=' + socket.fd + ', remote port=' + remote_port);
* bind_f(socket.fd, 11111, '127.0.0.2'); // put some random port
* });
*/
var timers = require('timers');
var last_port = null;
var o_active = timers.active;
var net = require('net');
var o_connect = net.Socket.prototype.connect;
net.Socket.prototype.connect = function() {
last_port = Number(arguments[0]);
o_connect.apply(this, arguments);
};
module.exports = function(callback) {
timers.active = function(obj) {
if (arguments.callee.caller.name == 'doConnect')
callback(obj, last_port);
o_active(obj);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment