How to determine if a host is available?

How to determine if a specific IP address is connected?

I need to write a small example node.jsthat tries to connect to ip:portand returns, trueor falsethereby determining whether the host is available or not.

+5
source share
2 answers

http.get

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/index.html'
};

http.get(options, function(res) {
  if (res.statusCode == 200) {
    console.log("success");
  }
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

function testPort(port, host, cb) {
  http.get({
    host: host, 
    port: port 
  }, function(res) {
    cb("success", res); 
  }).on("error", function(e) {
    cb("failure", e);
  });
}

To connect tcp just use net.createConnection

function testPort(port, host, cb) {
  net.createConnection(port, host).on("connect", function(e) {
    cb("success", e); 
  }).on("error", function(e) {
    cb("failure", e);
  });
}
+16
source

If you are only interested in HTTP, you can use the HTTP HEAD request (rather than POST / GET):

function hostAvailable(url) {
  var req = new XMLHttpRequest();
  req.open('HEAD', url, false);
  req.send();
  return req.status!=404;
}
-2
source

All Articles