Pinging Ports NodeJS

I am writing a status check for the hosting company I work for, we are wondering how we can check the port status using nodejs, if possible. If not, can you suggest any other ideas like using PHP and reading STDOUT?

+3
source share
2 answers

Yes, this is easily possible using the module net. Here is a brief example.

var net = require('net');
var hosts = [['google.com', 80], ['stackoverflow.com', 80], ['google.com', 444]];
hosts.forEach(function(item) {
    var sock = new net.Socket();
    sock.setTimeout(2500);
    sock.on('connect', function() {
        console.log(item[0]+':'+item[1]+' is up.');
        sock.destroy();
    }).on('error', function(e) {
        console.log(item[0]+':'+item[1]+' is down: ' + e.message);
    }).on('timeout', function(e) {
        console.log(item[0]+':'+item[1]+' is down: timeout');
    }).connect(item[1], item[0]);
});

Obviously, this can be improved. For example, it is currently breaking if the host cannot be resolved.

+9
source
    class ServiceMonitor {
    constructor( services){
        this.services = services
    }
    async monitor  () {
        let status = {
            url  : {},
            alias: {}
        }
        for ( let service of this.services ) {
            let isAlive = await this.ping ( service )
            status.url  [ '${service.address}:${service.port}' ] = isAlive
            status.alias[ service.service                      ] = isAlive
        }
        return status
    }
    ping ( connection ) {
        return new Promise ( ( resolve, reject )=>{
            var tcpp = require('tcp-ping');
            tcpp.ping( connection,function( err, data) {
                let error = data.results [0].err            
                if ( !error ) {
                    resolve ( true )
                }
                if ( error ) {
                    resolve ( false )
                }
            });
        })        
    }
}

( async function test () {
    let services = [
        {
            service : "redis_local",
            address : "localhost",
            port    : 6379,
            timeout : 1000,
            attempts: 1
        },
        {
            service : "redis_prod",
            address : "192.168.7.136",
            port    : 6379,
            timeout : 1000,
            attempts: 1
        },
        {
            service : "ussd_prod",
            address : "192.168.7.136",
            port    : 1989,
            timeout : 1000,
            attempts: 1
        },
        {
            service : "fraud_guard_prod",
            address : "192.168.7.136",
            port    : 1900,
            timeout : 1000,
            attempts: 1
        }
    ],
    status = await new ServiceMonitor ( services ).monitor ()
    console.log ( status )
}())
0
source

All Articles