17.11. Checking if a Host Is Alive17.11.1. ProblemYou want to ping a host to see if it is still up and accessible from your location. 17.11.2. Solutionrequire 'Net/Ping.php'; $ping = new Net_Ping; if ($ping->checkhost('www.oreilly.com')) { print 'Reachable'; } else { print 'Unreachable'; } $data = $ping->ping('www.oreilly.com'); 17.11.3. DiscussionThe ping program tries to send a message from your machine to another. If everything goes well, you get a series of statistics chronicling the transaction. An error means that ping can't reach the host for some reason. On error, Net_Ping::checkhost( ) returns false, and Net_Ping::ping( ) returns the constant PING_HOST_NOT_FOUND. If there's a problem running the ping program (because Net_Ping is really just a wrapper for the program), PING_FAILED is returned. If everything is okay, you receive an array similar to this: $results = $ping->ping('www.oreilly.com'); foreach($results as $result) { print "$result\n"; } PING www.oreilly.com (209.204.146.22) from 192.168.123.101 : 32(60) bytes of data. 40 bytes from www.oreilly.com (209.204.146.22): icmp_seq=0 ttl=239 time=96.704 msec 40 bytes from www.oreilly.com (209.204.146.22): icmp_seq=1 ttl=239 time=86.567 msec 40 bytes from www.oreilly.com (209.204.146.22): icmp_seq=2 ttl=239 time=86.563 msec 40 bytes from www.oreilly.com (209.204.146.22): icmp_seq=3 ttl=239 time=136.565 msec 40 bytes from www.oreilly.com (209.204.146.22): icmp_seq=4 ttl=239 time=86.627 msec -- - www.oreilly.com ping statistics -- - 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/mdev = 86.563/98.605/136.565/19.381 ms Net_Ping doesn't do any parsing of the data to pull apart the information, such as the packet loss percentage or the average round-trip time. However, you can parse it yourself: $results = $ping->ping('www.oreilly.com'); // grab last line of array; equivalent to non-destructive array_pop( ) // or $results[count($results) - 1] $round_trip = end($results); preg_match_all('#[ /]([.\d]+)#', $round_trip, $times); // pull out the data list($min,$avg,$max,$mdev) = $times[1]; // or print it out foreach($times[1] as $time) { print "$time\n"; } 83.229 91.230 103.223 7.485 This regular expression searches for either a space or a slash. It then captures a sequence of one or more numbers and a decimal point. To avoid escaping /, we use the # nonstandard character as your delimiter. 17.11.4. See AlsoPEAR's Net_Ping package at http://pear.php.net/package-info.php?package=Net_Ping. Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|