How to "Ping" from a Node.js app?

I want to ping a server from my node.js app.

Is that doable?

Thanks


You could use exec to call the system ping command

var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("ping -c 3 localhost", puts);

node-net-ping is an awesome module that uses raw sockets.

And, if you are looking for only raw sockets, the same developer has a module for that too: node-raw-socket.


I'm author of ping-wrapper.

It spawn ping and you can listen to events immediately. If process quits, it will be spawn automatically.


Doing ping(programmable) requires root privileges because it requires raws sockets which require root access. You could perform ping following Gradwohl's snippet, but keep in mind that you are forking a new process which is expensive(relatively). If you don't need to do it a lot(concurrency) this will definitely work :)

To do it in node.js(only) without forking process I think you have a couple of options, which are both hard to implement :()

  1. rewrite this ping python library to node.js and then run program as root user.
  2. write a c++ extension/addon for node.js using asio c++ library for node.js. It also has a couple of examples how to do icmp ping.

Not (only) using node.js:

  1. use python ping library ran as root and communicate with node.js instance via redis. => EASIEST to implement.(hardly any work but I think rather fast :))
  2. write c(++) code again using asio c++ but instead of writing node.js extension communicate via hiredis with node.js which also uses redis.

As a side-note how to use redis on node.js:

  • install redis from http://redis.io
  • install the fast node_redis library

You can also use my nodejs ping wrapper yaping. One day we will get raw sockets in nodejs and we'll be able to make our own ping packets and lie about our response times. ;-)

This simple function should

  • do dns lookups
  • ping once
  • timeout after 10 seconds
  • communicate all the well though out error codes that ping provides
  • spawn a child processes out of wedlock