Created
March 21, 2013 09:26
-
-
Save takeshy/5211784 to your computer and use it in GitHub Desktop.
node.jsで使っていないポートを取得する
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
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