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
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With