How to ping IP addresses using JavaScript

前端 未结 7 1448
遇见更好的自我
遇见更好的自我 2020-12-03 02:20

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.

H

7条回答
  •  臣服心动
    2020-12-03 02:45

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

提交回复
热议问题