Is it possible to ping a server from Javascript?

I have found someone that accomplishes this with a very clever usage of the native Image object.

From their source, this is the main function (it has dependences on other parts of the source but you get the idea).

function Pinger_ping(ip, callback) {

  if(!this.inUse) {

    this.inUse = true;
    this.callback = callback
    this.ip = ip;

    var _that = this;

    this.img = new Image();

    this.img.onload = function() {_that.good();};
    this.img.onerror = function() {_that.good();};

    this.start = new Date().getTime();
    this.img.src = "http://" + ip;
    this.timer = setTimeout(function() { _that.bad();}, 1500);

  }
}

This works on all types of servers that I’ve tested (web servers, ftp servers, and game servers). It also works with ports. If anyone encounters a use case that fails, please post in the comments and I will update my answer.

Update: Previous link has been removed. If anyone finds or implements the above, please comment and I’ll add it into the answer.

Update 2: @trante was nice enough to provide a jsFiddle.

http://jsfiddle.net/GSSCD/203/

Update 3: @Jonathon created a GitHub repo with the implementation.

https://github.com/jdfreder/pingjs

Update 4: It looks as if this implementation is no longer reliable. People are also reporting that Chrome no longer supports it all, throwing a net::ERR_NAME_NOT_RESOLVED error. If someone can verify an alternate solution I will put that as the accepted answer.

Leave a Comment