How to ping IP addresses using JavaScript

I want to run JavaScript code for ping 4 different IP addresses, and then get the packet loss and delay of these ping requests and display them on the page.

How to do it?

+7
source share
7 answers

You cannot do this from JS. What you can do is:

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

Make an AJAX request to your server, which will then host the target servers on you and return the result to the AJAX result.

Possible reservations:

  • this tells you if the target servers are pingable from your server, not from the user client
    • so that the client could not check the hosts on its local network
    • but you should not allow the host to check hosts on the internal network of the server, if they exist
    • Some hosts may block traffic from specific hosts, not others.
  • you need to limit the amount of ping for each machine:
    • to avoid AJAX request from timeout
    • Some site operators can be very frustrated when you constantly check your sites.
  • resources
    • Long-term HTTP requests may exceed your server’s maximum connection limit, check how high it is
    • many users trying to ping immediately can generate suspicious traffic (all ICMP and nothing more)
  • concurrency - you may want to combine / cache the status up / down for a few seconds, at least so that several clients who want to ping for the same purpose do not start the flow of letters.
+16
source

The only way I can think of is to download, for example. image file from an external server. When this download fails, you β€œknow” that the server is not responding (you actually do not know, because the server may just block you).

Take a look at this sample 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"; //eg logo -- mind the caching, maybe use a dynamic querystring if(ImageObject.height>0){ alert("Ping worked!"); } else { alert("Ping failed :("); } } 
+4
source

Closest you are going to connect to ping in JS using AJAX, and retrieve readistates, status and headers. Something like that:

 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 set conditions for different http statuses and draw a conclusion, however, with descriptions, etc., to make it more enjoyable. More checking the status of the http url than ping, but the same idea really. You can always loop it several times so that it looks more like ping for you :)

+2
source

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

This is a kind of "HTTP request", which, it seems to me, can be very useful for use with XMLHttpRequest () calls, for example, to find out which one is the fastest server in any case or to collect approximate statistics of the user's internet connection speed.

This small function simply connects to the HTTP server at a nonexistent URL (which is expected to return 404), then measures the time until the server responds to the HTTP request and does a cumulative time and number of iterations.

The requested URL is randomly modified on every call, as I noticed that (maybe) some transparent proxies or caching mechanisms, in which in some cases there are falsifications that give faster answers (faster than ICMP in fact, which is somewhat strange).

Beware of using FQDNs that match the real HTTP server! Results will be displayed in the body element with the identifier "result", for example:

 <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 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 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 example, starting with:

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

Please note that I could not find a simple relationship between the outcome metrics from this script and ICMP ping on the respective servers, although the HTTP response time seems to be roughly exponential from the ICMP response time. This can be explained by the amount of data that is transmitted through an HTTP request, which can vary depending on the taste and configuration of the web server, obviously, the speed of the server itself and, possibly, other reasons.

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

+2
source
 function ping(url){ new Image().src=url } 

Above pings given Url.
Commonly used for counters / analytics.
It will not face failed client responses (javascript)

+1
source

Is it possible to ping a server with Javascript?

The above solution should be checked. Pretty smooth.

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

-one
source

You cannot ping with javascript. I created a Java servlet that returns a green image of 10x10 pixels if it is live, and a red image if it is dead. https://github.com/pla1/Misc/blob/master/README.md

-2
source

All Articles