Skip to content

Instantly share code, notes, and snippets.

@ilio
Last active April 3, 2018 21:24
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 ilio/9d97054addc618c5a5b60eda43ab1db3 to your computer and use it in GitHub Desktop.
Save ilio/9d97054addc618c5a5b60eda43ab1db3 to your computer and use it in GitHub Desktop.
node.js scan open ports
// based on https://github.com/baalexander/node-portscanner/blob/master/lib/portscanner.js
const {Socket} = require('net');
function connect(port, host, timeout, callback) {
let connectionRefused = false;
const socket = new Socket();
let status = null;
let error = null;
// Socket connection established, port is open
socket.on('connect', function () {
status = 'open';
socket.destroy();
});
// If no response, assume port is not listening
socket.setTimeout(timeout);
socket.on('timeout', function () {
status = 'closed';
error = new Error('Timeout (' + timeout + 'ms) occurred waiting for ' + host + ':' + port + ' to be available');
socket.destroy();
});
// Assuming the port is not open if an error. May need to refine based on
// exception
socket.on('error', function (exception) {
if (exception.code !== 'ECONNREFUSED') {
error = exception;
} else {
connectionRefused = true;
}
status = 'closed';
});
// Return after the socket has closed
socket.on('close', function (exception) {
if (exception && !connectionRefused) {
error = error || exception;
} else {
error = null;
}
callback(error, status);
});
socket.connect(port, host);
}
async function connectAsync(port, host, timeout) {
return new Promise(resolve => {
connect(port, host, timeout, (error, status) => {
resolve({error, status, port, host});
});
});
}
async function connectAsyncRange(fromPort, toPort, host, timeout) {
const promises = [];
for (let port = fromPort; port < toPort; port++) {
promises.push(connectAsync(port, host, timeout));
}
return await Promise.all(promises);
}
// settings
const concurrentRequests = 100;
const host = '10.144.44.1';
const fromPort = 400;
const toPort = 65535;
(async () => {
const allOpenPorts = [];
for (let port = fromPort; port < toPort; port += concurrentRequests) {
const result = await connectAsyncRange(port, Math.min(toPort, port + concurrentRequests), host, 400);
const closedPorts = [];
const openPorts = [];
result.forEach(({error, status, port, host}) => {
if (status === 'open') {
openPorts.push(port);
allOpenPorts.push(port);
} else {
if (error) {
closedPorts.push(`${port} error: ${error}`);
} else {
closedPorts.push(port);
}
}
});
if (openPorts.length > 0) {
console.log('opened ports: ', openPorts.join(', '));
}
if (closedPorts.length > 0) {
console.log('closed ports: ', closedPorts.join(', '));
}
}
console.log('all opened ports for host', host, ' in range', fromPort, '-', toPort, ':', allOpenPorts.join(', '));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment