Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can check if server and port is available in nodejs ?

I have project with is written with Nodejs. I need to know how to check if an IP with Port is working to connect to.

EX: Check example1.com 443 =>true ; Check example1.com 8080 =>false

Thanks

like image 409
rubiken Avatar asked Dec 24 '22 21:12

rubiken


1 Answers

The only way to know if a server/port is available is to try to actually connect to it. If you knew that the server responded to ping, you could run a ping off the server, but that just tells you if the host is running and responding to ping, it doesn't directly tell you if the server process you want to connect to is running and accepting connections.

The only way to actually know that it is running and accepting connections is to actually connect to it and report back whether it was successful or not (note this is an asynchronous operation):

var net = require('net');
var Promise = require('bluebird');

function checkConnection(host, port, timeout) {
    return new Promise(function(resolve, reject) {
        timeout = timeout || 10000;     // default of 10 seconds
        var timer = setTimeout(function() {
            reject("timeout");
            socket.end();
        }, timeout);
        var socket = net.createConnection(port, host, function() {
            clearTimeout(timer);
            resolve();
            socket.end();
        });
        socket.on('error', function(err) {
            clearTimeout(timer);
            reject(err);
        });
    });
}

checkConnection("example1.com", 8080).then(function() {
    // successful
}, function(err) {
    // error
})
like image 58
jfriend00 Avatar answered Dec 28 '22 10:12

jfriend00