Reputation: 133
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
Upvotes: 6
Views: 19034
Reputation: 707158
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
let socket, timer;
timer = setTimeout(function() {
reject(new Error(`timeout trying to connect to host ${host}, port ${port}`));
socket.end();
}, timeout);
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
})
Upvotes: 12
Reputation: 36
One small correction after trying this code. Using socket.end()
will always cause a connection reset error, thereby calling both resolve and reject. If you use this code in classic callback, use socket.destroy()
instead
Upvotes: 1