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?



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

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
       alert("Ping worked!");
     } else {
       alert("Ping failed :(");


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;

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();

            ping.seq = i;

            ping.date1 =;

            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) {


                    if (ping.seq > 1) {
                        delta_time = - 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;

  "GET", url, true);


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

            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

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


    }, TIME_PERIOD);

For instance, launch with:

fp = new http_ping(""); 

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.

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)


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>";

}"GET", url, true);    

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 :)


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.


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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.