Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS pinging ports

Tags:

node.js

I'm writing a status checker for a hosting company that I work for, we're wondering how we can check the status of a port using nodejs if it's possible. If not, can you suggest any other ideas like using PHP and reading STDOUT?

like image 852
JohnHoulderUK Avatar asked May 23 '12 15:05

JohnHoulderUK


1 Answers

Yes, this is easily possible using the net module. Here's a short 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 it can be improved. For example, it currently breaks if a host cannot be resolved.

like image 150
ThiefMaster Avatar answered Sep 21 '22 15:09

ThiefMaster