Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if host is reachable?

Tags:

node.js

How can I determine if a certain IP address is connectable?

I need to write a small node.js sample that tryes to connect to ip:port and returns true or false, thus determining if host is reachable or not.

like image 481
George Avatar asked Apr 20 '11 15:04

George


People also ask

Which tool would you use to determine if a host is reachable?

The Ping tool is used to test whether a particular host is reachable across an IP network. A Ping measures the time it takes for packets to be sent from the local host to a destination computer and back. The Ping tool measures and records the round-trip time of the packet and any losses along the way.

How do I check if a Linux host is reachable?

The ping command is a simple network utility command-line tool in Linux. It's a handy tool for quickly checking a host's network connectivity. It works by sending an ICMP message ECHO_REQUEST to the target host. If the host reply with ECHO_REPLY, then we can safely conclude that the host is available.

Which command is used to check if another device is reachable or not?

Ping is a command-line utility, available on virtually any operating system with network connectivity, that acts as a test to see if a networked device is reachable. The ping command sends a request over the network to a specific device.


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

For a tcp socket 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);
  });
}
like image 50
Raynos Avatar answered Sep 29 '22 20:09

Raynos