How to ping IP addresses using JavaScript

前端 未结 7 1451
遇见更好的自我
遇见更好的自我 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:40

    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 = ""
    ping = new XMLHttpRequest();    
    ping.onreadystatechange = function(){
    
        document.body.innerHTML += "
    " + ping.readyState; if(ping.readyState == 4){ if(ping.status == 200){ result = ping.getAllResponseHeaders(); document.body.innerHTML += "
    " + result + "
    "; } } } 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 :)

提交回复
热议问题