Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 615
user434885 Avatar asked Feb 10 '11 08:02

user434885


1 Answers

I've come up with something cause I was bored of searching hours after hours for something that everyone is saying "impossible", only thing I've found was using jQuery. I've came up with a new simple way using Vanilla JS (nothing else than base JavaScript).

Here's my JSFiddle: https://jsfiddle.net/TheNolle/5qjpmrxg/74/

Basically, I create a variable called "start" which I give the timestamp, then I try to set an invisible image's source to my website (which isn't an image) [can be changed to any website], because it's not an image it creates an error, which I use to execute the second part of the code, at this time i create a new variable called "end" which i give the timestamp from here (which is different from "start"). Afterward, I simply make a substraction (i substract "start" from "end") which gives me the latency that it took to ping this website. After you have the choice you can store that in a value, paste it on your webpage, paste it in the console, etc.

let pingSpan = document.getElementById('pingSpan');
// Remove all the way to ...
let run;

function start() {
  run = true;
  pingTest();
}

function stop() {
  run = false;
  setTimeout(() => {
    pingSpan.innerHTML = "Stopped !";
  }, 500);
}

// ... here

function pingTest() {
  if (run == true) { //Remove line
    let pinger = document.getElementById('pingTester');
    let start = new Date().getTime();
    pinger.setAttribute('src', 'https://www.google.com/');
    pinger.onerror = () => {
      let end = new Date().getTime();
      // Change to whatever you want it to be, I've made it so it displays on the page directly, do whatever you want but keep the "end - start + 'ms'"
      pingSpan.innerHTML = end - start + "ms";
    }
    setTimeout(() => {
      pingTest();
    }, 1000);
  } // Remove this line too
}
body {
  background: #1A1A1A;
  color: white
}

img {
  display: none
}
Ping:
<el id="pingSpan">Waiting</el>
<img id="pingTester">

<br> <br>

<button onclick="start()">
  Start Ping Test
</button>
<button onclick="stop()">
  Stop
</button>
like image 174
TheNolle Avatar answered Oct 25 '22 10:10

TheNolle