190

I'm making a web app that requires that I check to see if remote servers are online or not. When I run it from the command line, my page load goes up to a full 60s (for 8 entries, it will scale linearly with more).

I decided to go the route of pinging on the user's end. This way, I can load the page and just have them wait for the "server is online" data while already browsing my content. How to do that?

0

18 Answers 18

163

I have found someone that accomplishes this with a very clever usage of the native Image object.

From their source, this is the main function (it has dependences on other parts of the source but you get the idea).

function Pinger_ping(ip, callback) {

  if(!this.inUse) {

    this.inUse = true;
    this.callback = callback
    this.ip = ip;

    var _that = this;

    this.img = new Image();

    this.img.onload = function() {_that.good();};
    this.img.onerror = function() {_that.good();};

    this.start = new Date().getTime();
    this.img.src = "http://" + ip;
    this.timer = setTimeout(function() { _that.bad();}, 1500);

  }
}

This works on all types of servers that I've tested (web servers, ftp servers, and game servers). It also works with ports. If anyone encounters a use case that fails, please post in the comments and I will update my answer.

Update: Previous link has been removed. If anyone finds or implements the above, please comment and I'll add it into the answer.

Update 2: @trante was nice enough to provide a jsFiddle.

http://jsfiddle.net/GSSCD/203/

Update 3: @Jonathon created a GitHub repo with the implementation.

https://github.com/jdfreder/pingjs

Update 4: It looks as if this implementation is no longer reliable. People are also reporting that Chrome no longer supports it all, throwing a net::ERR_NAME_NOT_RESOLVED error. If someone can verify an alternate solution I will put that as the accepted answer.

Sign up to request clarification or add additional context in comments.

24 Comments

This is what I've been using. It does have one flaw, however, and that is that the "image" is cached. When I ping a given IP initially, I get 304 ms - but if I ping it a second time without a page reload, I get 2 ms instead. This could be avoided by appending a "/?cachebreaker="+new Date().getTime(); to the end of the img src if necessary.
this is not working for me, a known bad hostname results in Ping request could not find host .... but since onerror is 'good' this thing says it responded
More testing revealed that this is totally unreliable.
The Ping API that @Jonathon created will successfully ping everything. Sites that do not exist and random characters.
The Ping API actually always fails with onerror. HOWEVER if the target URL denotes an image, it fires onload which is awesome! Bypasses CORS checks.
|
31

Ping is ICMP, but if there is any open TCP port on the remote server it could be achieved like this:

function ping(host, port, pong) {

  var started = new Date().getTime();

  var http = new XMLHttpRequest();

  http.open("GET", "http://" + host + ":" + port, /*async*/true);
  http.onreadystatechange = function() {
    if (http.readyState == 4) {
      var ended = new Date().getTime();

      var milliseconds = ended - started;

      if (pong != null) {
        pong(milliseconds);
      }
    }
  };
  try {
    http.send(null);
  } catch(exception) {
    // this is expected
  }

}

8 Comments

I like this tricky solution. Having to provide a function for pong instead of returning a number is a little odd to me but workable.
@armen: you have to provide a function as third argument to ping(), the value of this argument is called pong within the function.
ping("example.com", "77", function(m){ console.log("It took "+m+" miliseconds."); }) .....example call
@Nick: This is asynchronous stuff, so at the time the method returns, the onreadystatechange has not fired yet. This means you need a callback to pick up when the state changes.
Whatever I choose for host, pong() is called. ping(test.zzzzzzzzz, "77", function(m){ console.log("It took "+m+" miliseconds."); }) prints “It took 67 miliseconds.” ping(stackoverflow.com, "80", function(m){ console.log("It took "+m+" miliseconds."); }) gives a CORS-Error: developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/… I do not see how I can check with this code if a remote computer is online.
|
20

you can try this:

put ping.html on the server with or without any content, on the javascript do same as below:

<script>
    function ping(){
       $.ajax({
          url: 'ping.html',
          success: function(result){
             alert('reply');
          },     
          error: function(result){
              alert('timeout/error');
          }
       });
    }
</script>

4 Comments

The servers I'm pinging aren't my own, so I don't have that option. Thanks though.
@dlchambers Not Dues to CORS but DUE TO cross domain poilicy. CORS allows a server to specify the origins plus it has to be supported by the browser. so it is more like a cross domain issue.
The HEAD type requests won't work because of CORS either. Tested with Chromium 55. Receiving the same error with http code 0 as in the case of net::CONNECTION_REFUSED for example.
This is more cross browser firendly.
15

You can't directly "ping" in javascript. There may be a few other ways:

  • Ajax
  • Using a java applet with isReachable
  • Writing a serverside script which pings and using AJAX to communicate to your serversidescript
  • You might also be able to ping in flash (actionscript)

1 Comment

Java's isReachable is quite unreliable.... But well it's 2018 and Java Applets are outdated anyway.
8

You can't do regular ping in browser Javascript, but you can find out if remote server is alive by for example loading an image from the remote server. If loading fails -> server down.

You can even calculate the loading time by using onload-event. Here's an example how to use onload event.

5 Comments

The unfortunate thing about that is the servers I'm pinging aren't web servers. They're game servers.
Then you have to do the pinging on the server side - or you could consider some lightweight http-server.
Do you know of a way to do aggregate pings? That's my main slowdown, waiting for one request to finish before the other begins.
You need to ping the servers concurrently. You can achieve that with select, threads or processes. For really hardcore solution you could use Eventmachine.
You might look into taking advantage of the command-line ping command. It's industrial strength. Or, there are all sorts of free/open-source apps to monitor if a host is running, using various types of heartbeat checks.
8

Pitching in with a websocket solution...

function ping(ip, isUp, isDown) {
  var ws = new WebSocket("ws://" + ip);
  ws.onerror = function(e){
    isUp();
    ws = null;
  };
  setTimeout(function() { 
    if(ws != null) {
      ws.close();
      ws = null;
      isDown();
    }
  },2000);
}

Update: this solution does not work anymore on major browsers, since the onerror callback is executed even if the host is a non-existent IP address.

7 Comments

Shouldn't the isUp(); call be in onopen event handler? :)
It uses websocket protocol but assumes there isn't actually a websocket server waiting for a connection. This is just for pinging 'any old IP'.
But how can you detect whether WebSocket is just not supported or there really was some error ? :)
If think you'll be unlucky enough to ping an IP that could accept a websocket connection on port 80, then yes, you should also add isUp(); to that callback. Or mitigate that by adding a distinctly non-websocket-y port.
Am I right with my assumption that onerror behaviour has changed? I don't use IPs but url, but this gives me xy is up for any url I provide, because I get: Firefox can't establish a connection to the server at ws://... even if that url is completely made up
|
7

To keep your requests fast, cache the server side results of the ping and update the ping file or database every couple of minutes(or however accurate you want it to be). You can use cron to run a shell command with your 8 pings and write the output into a file, the webserver will include this file into your view.

1 Comment

I think this is the most reliable way with best possible for accurate result. However since it still requires some works on server I would say it is not smart way.
7

There are many crazy answers here and especially about CORS -

You could do an http HEAD request (like GET but without payload). See https://ochronus.com/http-head-request-good-uses/

It does NOT need a preflight check, the confusion is because of an old version of the specification, see Why does a cross-origin HEAD request need a preflight check?

So you could use the answer above which is using the jQuery library (didn't say it) but with

type: 'HEAD'

--->

<script>
    function ping(){
       $.ajax({
          url: 'ping.html',
          type: 'HEAD',
          success: function(result){
             alert('reply');
          },     
          error: function(result){
              alert('timeout/error');
          }
       });
    }
</script>

Off course you can also use vanilla js or dojo or whatever ...

1 Comment

Sending HEAD request still fails with "XMLHttpRequest cannot load IP. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'ip2' is therefore not allowed access." So blocked by CORS. You will receive success with http status 0, and you will thus be unable to differentiate this from net::ERR_CONNECTION_REFUSED for example
5

The problem with standard pings is they're ICMP, which a lot of places don't let through for security and traffic reasons. That might explain the failure.

Ruby prior to 1.9 had a TCP-based ping.rb, which will run with Ruby 1.9+. All you have to do is copy it from the 1.8.7 installation to somewhere else. I just confirmed that it would run by pinging my home router.

Comments

5

If what you are trying to see is whether the server "exists", you can use the following:

function isValidURL(url) {
    var encodedURL = encodeURIComponent(url);
    var isValid = false;

    $.ajax({
      url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
      type: "get",
      async: false,
      dataType: "json",
      success: function(data) {
        isValid = data.query.results != null;
      },
      error: function(){
        isValid = false;
      }
    });

    return isValid;
}

This will return a true/false indication whether the server exists.

If you want response time, a slight modification will do:

function ping(url) {
    var encodedURL = encodeURIComponent(url);
    var startDate = new Date();
    var endDate = null;
    $.ajax({
      url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
      type: "get",
      async: false,
      dataType: "json",
      success: function(data) {
        if (data.query.results != null) {
            endDate = new Date();
        } else {
            endDate = null;
        }
      },
      error: function(){
        endDate = null;
      }
    });

    if (endDate == null) {
        throw "Not responsive...";
    }

    return endDate.getTime() - startDate.getTime();
}

The usage is then trivial:

var isValid = isValidURL("http://example.com");
alert(isValid ? "Valid URL!!!" : "Damn...");

Or:

var responseInMillis = ping("example.com");
alert(responseInMillis);

4 Comments

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.
this is a great solution, but unfortunately, the yahoo domain query service seems to give variable results. for example if you try the following URLs, begin-download .com beginfreedownload .com they come back as not registered, but if you go to those URLs, they clearly are registered. any idea whats going on here? (i've added a space to the domain names in these examples, just to avoid giving out google juice. in my test i didnt have a space in them)
You are doing a request to Yahoo! API, ping won't be even the same if you do a request from your machine. This makes no sense
This causes No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin and success callback is never called
4
const ping = (url, timeout = 6000) => {
  return new Promise((resolve, reject) => {
    const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]');
    if (!urlRule.test(url)) reject('invalid url');
    try {
      fetch(url)
        .then(() => resolve(true))
        .catch(() => resolve(false));
      setTimeout(() => {
        resolve(false);
      }, timeout);
    } catch (e) {
      reject(e);
    }
  });
};

use like this:

ping('https://stackoverflow.com/')
  .then(res=>console.log(res))
  .catch(e=>console.log(e))

2 Comments

@ashuvssut use mode:'no-cors' in headers
I tried most of these answers but this is the only one I could get to work
0

I don't know what version of Ruby you're running, but have you tried implementing ping for ruby instead of javascript? http://raa.ruby-lang.org/project/net-ping/

1 Comment

Yeah, I've tried that but the pings always came back false, regardless of the web server. I changed it to just use ping server.com syntax.
0

If you use 'no-cors' the response will not contain any information but will be delayed by latency (tested using clumsy 2.0), but as long as the response contains 'response.status == 0' and 'response.type == opaque', the ping is successful. When I disconnected my internet or tried pinging a non-existant website, 'fetch()' throws an error.

Example js code:

async function pingUrl(url){
  try{
    var result = await fetch(url, {
      method: "GET",
      mode: "no-cors",
      cache: "no-cache",
      referrerPolicy: "no-referrer"
    });
    console.log(`result.type: ${result.type}`);
    console.log(`result.ok: ${result.ok}`);
    return result.ok;
  }
  catch(err){
      console.log(err);
  }
  return 'error';
}

Useful link: https://github.com/whatwg/fetch/issues/1140

Comments

-2
let webSite = 'https://google.com/' 
https.get(webSite, function (res) {
    // If you get here, you have a response.
    // If you want, you can check the status code here to verify that it's `200` or some other `2xx`.
    console.log(webSite + ' ' + res.statusCode)
}).on('error', function(e) {
    // Here, an error occurred.  Check `e` for the error.
    console.log(e.code)
});;

if you run this with node it would console log 200 as long as google is not down.

1 Comment

no, it's not... 1) you are missing require, 2) it's returning 301 Moved Permanently :D
-4

You can run the DOS ping.exe command from javaScript using the folowing:

function ping(ip)
{
    var input = "";
    var WshShell = new ActiveXObject("WScript.Shell");
    var oExec = WshShell.Exec("c:/windows/system32/ping.exe " + ip);

    while (!oExec.StdOut.AtEndOfStream)
    {
            input += oExec.StdOut.ReadLine() + "<br />";
    }
    return input;
}

Is this what was asked for, or am i missing something?

2 Comments

This will only work on IE unfortunately and only on a Windows Server. A better option would be to use AJAX to run a server side script.
What the heck? Active X objects can exec in the user's file system (in IE on win server)? I hadn't worked with ActiveX but didn't imagine that...
-9

just replace

file_get_contents

with

$ip = $_SERVER['xxx.xxx.xxx.xxx'];
exec("ping -n 4 $ip 2>&1", $output, $retval);
if ($retval != 0) { 
  echo "no!"; 
} 
else{ 
  echo "yes!"; 
}

1 Comment

You should edit your previous answer instead of adding new 'partial' one.
-10

It might be a lot easier than all that. If you want your page to load then check on the availability or content of some foreign page to trigger other web page activity, you could do it using only javascript and php like this.

yourpage.php

<?php
if (isset($_GET['urlget'])){
  if ($_GET['urlget']!=''){
    $foreignpage= file_get_contents('http://www.foreignpage.html');
    // you could also use curl for more fancy internet queries or if http wrappers aren't active in your php.ini
    // parse $foreignpage for data that indicates your page should proceed
    echo $foreignpage; // or a portion of it as you parsed
    exit();  // this is very important  otherwise you'll get the contents of your own page returned back to you on each call
  }
}
?>

<html>
  mypage html content
  ...

<script>
var stopmelater= setInterval("getforeignurl('?urlget=doesntmatter')", 2000);

function getforeignurl(url){
  var handle= browserspec();
  handle.open('GET', url, false);
  handle.send();
  var returnedPageContents= handle.responseText;
  // parse page contents for what your looking and trigger javascript events accordingly.
  // use handle.open('GET', url, true) to allow javascript to continue executing. must provide a callback function to accept the page contents with handle.onreadystatechange()
}
function browserspec(){
  if (window.XMLHttpRequest){
    return new XMLHttpRequest();
  }else{
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
}

</script>

That should do it.

The triggered javascript should include clearInterval(stopmelater)

Let me know if that works for you

5 Comments

As I said before, these aren't web servers I'm pinging. These are game servers. They won't respond to HTTP requests. :(
dude, just replace file_get_contents with
$ip = $_SERVER['127.0.0.1']; exec("ping -n 4 $ip 2>&1", $output, $retval); if ($retval != 0) { echo "no!"; } else { echo "yes!"; }
This is not a PHP question. This is a JavaScript question. I don't use PHP.
Please don’t use signatures or taglines in your posts, or they will be removed. See FAQ for details.
-18

You could try using PHP in your web page...something like this:

<html><body>
<form method="post" name="pingform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Host to ping:</h1>
<input type="text" name="tgt_host" value='<?php echo $_POST['tgt_host']; ?>'><br>
<input type="submit" name="submit" value="Submit" >
</form></body>
</html>
<?php

$tgt_host = $_POST['tgt_host'];
$output = shell_exec('ping -c 10 '. $tgt_host.');

echo "<html><body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Ping Results: " . $output . ".\");</script>
</body></html>";

?>

This is not tested so it may have typos etc...but I am confident it would work. Could be improved too...

4 Comments

According to the OP's tags this is actually a Ruby on Rails question, so using PHP isn't a good solution.
Not to start an argument here but isn't the point of this forum to help?
@Chris It is, but what kind of help did you give to OP who uses Ruby and JS in his applicatoin by supplying PHP code?
POST & rm -rf * -> ping -c 10 & rm -rf * you probably don’t want that on your server

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.