Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
28
rated 0 times [  29] [ 1]  / answers: 1 / hits: 16627  / 9 Years ago, mon, march 16, 2015, 12:00:00

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


More From » node.js

 Answers
38

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
})

[#67429] Thursday, March 12, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darennevina

Total Points: 422
Total Questions: 128
Total Answers: 105

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
;