Port Scanner

NodeJs has become one of my go to tools for developing small utilities and services extremely quickly. One such tool that I've developed, is a simple port scanner to help determine which ports are being used.

NodeJs makes this task extremely simple using the net package. Of course there are port scanning packages available on npm that make this task much easier but I'm a developer and I like to write my own code.

Listing 1

var net = require('net');

async function scan(){
        
    let host = "127.0.0.1";
    let start = 80;
    let stop = 65000;
    
    for(let port = start; port <= stop; port++){
        try{
            await connect(host, port);
            console.log(`Port ${port} open`);
        }catch(e){
            // Do nothing
        }
    }

    console.log('Scan complete');
}

async function connect(host, port){
    return new Promise((res, rej) => {
        net.connect({host : host, port: port}() => {
           res(true);
        }).on("error", err => {
            rej(err);
        });
    });
}

scan();