9

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?

Yi Jiang
  • 46,385
  • 16
  • 133
  • 131
user434885
  • 1,900
  • 6
  • 28
  • 49
  • Related to [this question](http://stackoverflow.com/questions/4954587/getting-client-to-automatically-send-data-to-server). – Linus Kleen Feb 10 '11 at 08:18
  • http://stackoverflow.com/questions/4282151/is-it-possible-to-ping-a-server-from-javascript Should check out the above solution. Pretty slick. – Jeffrey Tackett Apr 16 '17 at 21:50

7 Answers7

20

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
mcint
  • 517
  • 4
  • 10
Piskvor left the building
  • 87,797
  • 43
  • 170
  • 220
5

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 :(");
     }

}
Dennis G
  • 20,757
  • 17
  • 90
  • 129
  • 7
    That's not ping, that's an HTTP request (therefore TCP/IP). Also, if the target doesn't run an HTTP server, the request will take a *loooong* time to time out; plus, the loading is asynchronous - unless the image is already in cache, ImageObject.height will return 0 if you check it right after setting the `src`; and if it *is* in cache, it will return "Ping worked", whether the target is up or not. http://en.wikipedia.org/wiki/Ping – Piskvor left the building Feb 10 '11 at 08:34
  • 1
    Relax Piskvor - you are perfectly correct that this is not a REAL ping (neither is your solution) - you would need to be able to open sockets and send arbitrary TCP/IP packets to simulate a ping - I just called the method ping for simplicity. You are also correct that if the target doesn't run an HTTP server it will take a long time - hence I wrote "URL to a known image"... Also caching is an issue. This was a **simple** demonstration of an approach you could take, same principle as CSS history hacks. Thanks for the downvote. – Dennis G Feb 10 '11 at 10:26
  • Don't take the downvote personally, I didn't downvote *you*; I just felt that it doesn't really answer the question - although it *is* a simple way of checking if a known HTTP server might be up, it doesn't really answer the ping loss or latency. I agree that my approach is not pinging from the client's computer, that would require a lot of lowered permissions and many security holes (and ActiveX). – Piskvor left the building Feb 10 '11 at 11:11
  • Not taking it personally :-) Thanks for the follow-up – Dennis G Feb 10 '11 at 15:35
  • 3
    **Warning:** The above will cache. Be sure to append something unique to the end of the URL. Also, a lone IP/Domain will work just as well for the image `src`: `"http://" + ipOrHost + "?pingedat=" + new Date().getTime();`. – fny Sep 30 '12 at 21:40
4

I was inspired by the latest comment, so I wrote this quick piece of code.

This is a kind of "HTTP ping" which I think can be quite useful to use along with XMLHttpRequest calls(), for instance to figure out which is the fastest server to use in some case or to collect some rough statistics from the user's internet connexion speed.

This small function is just connecting to an HTTP server on an non-existing URL (that is expected to return a 404), then is measuring the time until the server is answering to the HTTP request, and is doing an average on the cumulated time and the number of iterations.

The requested URL is modified randomely at each call since I've noticed that (probably) some transparent proxies or caching mechanisms where faking results in some cases, giving extra fast answers (faster than ICMP actually which somewhat weird).

Beware to use FQDNs that fit a real HTTP server! Results will display to a body element with id "result", for instance:

<div id="result"></div>

Function code:

function http_ping(fqdn) {

var NB_ITERATIONS = 4; // number of loop iterations
var MAX_ITERATIONS = 5; // beware: the number of simultaneous XMLHttpRequest is limited by the browser!
var TIME_PERIOD = 1000; // 1000 ms between each ping
var i = 0;
var over_flag = 0;
var time_cumul = 0;
var REQUEST_TIMEOUT = 9000;
var TIMEOUT_ERROR = 0;

document.getElementById('result').innerHTML = "HTTP ping for " + fqdn + "</br>";

var ping_loop = setInterval(function() {


        // let's change non-existent URL each time to avoid possible side effect with web proxy-cache software on the line
        url = "http://" + fqdn + "/a30Fkezt_77" + Math.random().toString(36).substring(7);

        if (i < MAX_ITERATIONS) {

            var ping = new XMLHttpRequest();

            i++;
            ping.seq = i;
            over_flag++;

            ping.date1 = Date.now();

            ping.timeout = REQUEST_TIMEOUT; // it could happen that the request takes a very long time

            ping.onreadystatechange = function() { // the request has returned something, let's log it (starting after the first one)

                if (ping.readyState == 4 && TIMEOUT_ERROR == 0) {

                    over_flag--;

                    if (ping.seq > 1) {
                        delta_time = Date.now() - ping.date1;
                        time_cumul += delta_time;
                        document.getElementById('result').innerHTML += "</br>http_seq=" + (ping.seq-1) + " time=" + delta_time + " ms</br>";
                    }
                }
            }


            ping.ontimeout = function() {
                TIMEOUT_ERROR = 1;
            }

            ping.open("GET", url, true);
            ping.send();

        }

        if ((i > NB_ITERATIONS) && (over_flag < 1)) { // all requests are passed and have returned

            clearInterval(ping_loop);
            var avg_time = Math.round(time_cumul / (i - 1));
            document.getElementById('result').innerHTML += "</br> Average ping latency on " + (i-1) + " iterations: " + avg_time + "ms </br>";

        }

        if (TIMEOUT_ERROR == 1) { // timeout: data cannot be accurate

            clearInterval(ping_loop);
            document.getElementById('result').innerHTML += "<br/> THERE WAS A TIMEOUT ERROR <br/>";
            return;

        }

    }, TIME_PERIOD);
}

For instance, launch with:

fp = new http_ping("www.linux.com.au"); 

Note that I couldn't find a simple corelation between result figures from this script and the ICMP ping on the corresponding same servers, though HTTP response time seems to be roughly-exponential from ICMP response time. This may be explained by the amount of data that is transfered through the HTTP request which can vary depending on the web server flavour and configuration, obviously the speed of the server itself and probably other reasons.

This is not very good code but I thought it could help and possibly inspire others.

Gwen Wing
  • 73
  • 1
  • 7
2

The closest you're going to get to a ping in JS is using AJAX, and retrieving the readystates, status, and headers. Something like this:

url = "<whatever you want to ping>"
ping = new XMLHttpRequest();    
ping.onreadystatechange = function(){

    document.body.innerHTML += "</br>" + ping.readyState;

    if(ping.readyState == 4){
        if(ping.status == 200){
            result = ping.getAllResponseHeaders();
            document.body.innerHTML += "</br>" + result + "</br>";
        }
    }

}
ping.open("GET", url, true);    
ping.send();

Of course you can also put conditions in for different http statuses, and make the output display however you want with descriptions etc, to make it look nicer. More of an http url status checker than a ping, but same idea really. You can always loop it a few times to make it feel more like a ping for you too :)

Securis
  • 29
  • 1
  • Ide of using AJAX and retrieving the ready states is works for me. May I please ask how can I add a else statemen in this content. Like if the url is not available I would like to print a massage to user. Like document.getElementById("div").innerHTML = "Ping is not success!"; – Ibrahim İnce Nov 10 '16 at 17:41
1
function ping(url){
 new Image().src=url
}

Above pings the given Url.
Generally used for counters / analytics.
It won't encounter failed responses to client(javascript)

Dinesh
  • 1,058
  • 9
  • 6
0

Is it possible to ping a server from Javascript?

Should check out the above solution. Pretty slick.

Not mine, obviously, but wanted to make that clear.

Community
  • 1
  • 1
Jeffrey Tackett
  • 151
  • 1
  • 8
  • Down voting this answer doesn't make sense. The question was how to ping using Javascript, and the link shows you how to effectively ping using Javascript. Not sure what else someone could expect. Thanks for the rep subtraction though, much appreciated. Wow. – Jeffrey Tackett Aug 15 '17 at 02:47
-2

You can't PING with Javascript. I created Java servlet that returns a 10x10 pixel green image if alive and a red image if dead. https://github.com/pla1/Misc/blob/master/README.md

PLA
  • 345
  • 7
  • 14