PING using php

I have been playing around with CURL and its awesomeness for a potential idea and had to use some data retrieved by sending a ICMP packet to the host. This was required to check to check stuff like host availability, packet loss etc. The standard stuff. Doing this would be fairly straightforward if you wanted to use the exec function. However getting the data back as a data structure can be a pain.
Pear has an interesting packge Net/Ping does does all that very neatly for you. Here is the code snippet for that.

<?php
     require_once "Net/Ping.php";
     $ping = Net_Ping::factory();
     if(PEAR::isError($ping)) {
      echo $ping->getMessage();
    } else {
      /* Number of packets to send */
      $ping->setArgs(array('count' => 4));
      $rawData = $ping->ping('rajatpandit.com');
      print_r($rawData);
    }

?>

and the data that you get back, is a pretty useful structured array.

Net_Ping_Result Object
(
    [_icmp_sequence] => Array
        (
            [1] => 310
            [2] => 300
            [3] => 318
            [4] => 301
        )

    [_target_ip] => 67.205.0.93
    [_bytes_per_request] => 32
    [_bytes_total] => 128
    [_ttl] => 238
    [_raw_data] => Array
        (
            [0] =>
            [1] => Pinging rajatpandit.com [67.205.0.93] with 32 bytes of data:
            [2] =>
            [3] => Reply from 67.205.0.93: bytes=32 time=310ms TTL=238
            [4] => Reply from 67.205.0.93: bytes=32 time=300ms TTL=238
            [5] => Reply from 67.205.0.93: bytes=32 time=318ms TTL=238
            [6] => Reply from 67.205.0.93: bytes=32 time=301ms TTL=238
            [7] =>
            [8] => Ping statistics for 67.205.0.93:
            [9] =>     Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
            [10] => Approximate round trip times in milli-seconds:
            [11] =>     Minimum = 300ms, Maximum = 318ms, Average = 307ms
        )

    [_sysname] => windows
    [_round_trip] => Array
        (
            [min] => 300
            [max] => 318
            [avg] => 307
        )

    [_transmitted] => 4
    [_received] => 4
    [_loss] => 0
)

Sweet!

About rp

Architect for large, highly scalable LAMP applications and Technical Manager with special focus on metrics based continuous improvement of teams and products. Rajat has close to a decade of experience of a very wide range of skills related to infrastructure, middleware, app servers all the way to front-end technologies and software development methodologies including agile, iterative waterfall, waterfall as well as ah-hoc startup using the right approach in the right context to reduce time to market.