Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
const net = require('net');
function searchport(host, port, retry_count, callback) {
if (retry_count == null) {
retry_count = 100;
}
var socket = new net.Socket();
return new Promise(
function (resolve, reject) {
socket.on(
'error',
function (e) {
resolve(port);
if (callback) {
callback(null, port);
}
}
);
socket.connect(
port,
host,
function () {
socket.destroy();
reject('no free port');
}
);
}
).catch(
function (err) {
if (retry_count > 1) {
return searchport(host, port + 1, retry_count - 1, callback);
}
else {
if (callback) {
callback(err, null);
}
else {
throw err;
}
}
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment