2

I am pinging an array of 12 machines by ip address and displaying the status (host is alive or not) on a simple web interface. This is the code that I currently have -

$hosts = array ("192.168.0.100","192.168.0.101","192.168.0.102"); //etc.. 

foreach ($hosts as $hosts) {
    exec ("ping -i 1 -n 2 -l 1 $hosts", $ping_output);
    if(preg_match("/Reply/", $ping_output[2])) {
        echo "$hosts replied! <br />";
    } else {
        echo "$hosts did not reply! <br />";
    }
}

This works, but does not scale very well. I have to wait about 15 seconds before the page loads because it's pinging all machines and takes time. I reduce the ping count to only 2 replies, lowered the buffer size as well.

Is there a better approach to this? More efficient? Better than 15 seconds? Any suggestions are appreciated.

Thanks

Luffy
  • 1,317
  • 1
  • 19
  • 41
Charlie
  • 45
  • 6
  • maybe some combination of output buffering and web sockets? [example someone else had](http://stackoverflow.com/questions/1281140/run-process-with-realtime-output-in-php) – castis Sep 21 '15 at 21:13
  • Have you thought about using Javascript? It might be a better fit here if you can ping the servers from the client. – HPierce Sep 21 '15 at 21:13

1 Answers1

3

PHP won't be the slow part here, the system ping command will be. Consider the worst case scenario where all of the hosts are offline. You're going to have a minimum waiting time of TTL * NumHosts.

A better solution would be having a background process running that pings the hosts every X seconds and updates some sort of status marker (flat file, database table, etc). The outward facing page will read those status markers instantly and the information will never be more than X seconds old. This also has the added benefit of potentially reducing strain on your server and the target hosts by limiting the amount of pinging that occurs.

If that setup is not a viable option, your best bet is to fiddle with the ping options or find a different tool.

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
  • I found a faster tool called FPing.exe. How can I tell PHP to use FPing instead of ping.exe ? – Charlie Sep 22 '15 at 19:08
  • If `FPing` is in your `PATH` environment variable, simply use `FPing` in place of `ping` in your `exec()`. If it is not, you'll need to use the full path to `FPing`, like `C:\Path\To\Program\FPing.exe` – Mr. Llama Sep 22 '15 at 19:13
  • Thanks for the reply. I set: exec ('"C:/Server/Apache24/htdocs/C919Test/Fping.exe" $hosts -n 2 -t 1 -s 5', $fping_output); But no go. I bet it's a simple fix, like use double \\ instead? – Charlie Sep 22 '15 at 19:48