Skip to content

Instantly share code, notes, and snippets.

@takeshy
Created March 21, 2013 09:26
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 takeshy/5211784 to your computer and use it in GitHub Desktop.
Save takeshy/5211784 to your computer and use it in GitHub Desktop.
node.jsで使っていないポートを取得する
function getPort(host,port,maxPort,callback) {
var net = require('net');
var socket = new net.Socket();
socket.on('error', function(e) {
if(e.code == 'ECONNREFUSED'){
callback(null, port);
return;
}
loop(++port);
});
function loop(np) {
if (np > maxPort) {
callback(new Error('empty port not found'));
return;
}
socket.connect(np, host, function() {
socket.destroy();
port = np+1;
loop(port);
});
};
loop(port);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment