Reputation: 45
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
Upvotes: 2
Views: 1868
Reputation: 20909
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.
Upvotes: 3