How to ping IP addresses using JavaScript

I want to run a JavaScript code to ping 4 different IP addresses and then retrieve the packet loss and latency of these ping requests and display them on the page.

How do I do this?


Solution 1:

You can't do this from JS. What you could do is this:

 client --AJAX-- yourserver --ICMP ping-- targetservers

Make an AJAX request to your server, which will then ping the target servers for you, and return the result in the AJAX result.

Possible caveats:

  • this tells you whether the target servers are pingable from your server, not from the user's client
    • so the client won't be able to test hosts its LAN
    • but you shouldn't let the host check hosts on the server's internal network, if any exist
    • some hosts may block traffic from certain hosts and not others
  • you need to limit the ping count per machine:
    • to avoid the AJAX request from timing out
    • some site operators can get very upset when you keep pinging their sites all the time
  • resources
    • long-running HTTP requests could run into maximum connection limit of your server, check how high it is
    • many users trying to ping at once might generate suspicious-looking traffic (all ICMP and nothing else)
  • concurrency - you may wish to pool/cache the up/down status for a few seconds at least, so that multiple clients wishing to ping the same target won't launch a flood of pings

Solution 2:

The only method I can think of is loading e.g. an image file from the external server. When that load fails, you "know" the server isn't responding (you actually don't know, because the server could just be blocking you).

Take a look at this example code to see what I mean:

 /*note that this is not an ICMP ping - but a simple HTTP request
    giving you an idea what you could do . In this simple implementation it has flaws
    as Piskvor correctly points out below */
    function ping(extServer){
     var ImageObject = new Image();
     ImageObject.src = "http://"+extServer+"/URL/to-a-known-image.jpg"; //e.g. logo -- mind the caching, maybe use a dynamic querystring
     if(ImageObject.height>0){
       alert("Ping worked!");
     } else {
       alert("Ping failed :(");
     }

}