Pinging an IP in WordPress/PHP – getting results

I am trying to get a piece of script, which can be used to test a website is accessible, and display this result. I have a private server, which I can also test with. But for now, lets just say google.

I have tried many ways to do this:

Read More

First attempt was with Javascript – https://gist.github.com/jerone/3487795

    /* 
Ping 
*/
$.extend($, {
    Ping: function Ping(url, timeout) {
        timeout = timeout || 1500;
        var timer = null;

        return $.Deferred(function deferred(defer) {

            var img = new Image();
            img.onload = function () { success("onload"); };
            img.onerror = function () { success("onerror"); };  // onerror is also success, because this means the domain/ip is found, only the image not;

            var start = new Date();
            img.src = url += ("?cache=" + +start);
            timer = window.setTimeout(function timer() { fail(); }, timeout);

            function cleanup() {
                window.clearTimeout(timer);
                timer = img = null;
            }

            function success(on) {
                cleanup();
                defer.resolve(true, url, new Date() - start, on);
            }

            function fail() {
                cleanup();
                defer.reject(false, url, new Date() - start, "timeout");
            }

        }).promise();
    }
});
/* example */
$.Ping("http://google.com" /*, optional timeout */).done(function (success, url, time, on) {
    console.log("ping done", arguments);
}).fail(function (failure, url, time, on) {
    console.log("ping fail", arguments);
});

But this displayed true no matter what.

The next example was with PHP:

    function pingAddress($ip) {
    $pingresult = exec("/bin/ping -c2 -w2 $ip", $outcome, $status);  
    if ($status==0) {
    $status = "alive";
    } else {
    $status = "dead";
    }
    $message .= '<div id="dialog-block-left">';
    $message .= '<div id="ip-status">The IP address, '.$ip.', is  '.$status.'</div><div style="clear:both"></div>';    
    return $message;
}
// Some IP Address
pingAddress("192.168.1.1"); 

But again, always displayed as alive.
I am trying to access a private server which I DO NOT HAVE ACCESS TO. So this means I shouldn’t be able to ping this.

Any ideas/suggestions/improvements are more than welcome.

Related posts

3 comments

  1. You can also try

    $fp = fSockOpen($ip,80,$errno,$errstr,1);
    if($fp) { $status=0; fclose($fp); } else { $status=1; }
    

    Referred from here.

  2. $status will only returns the status of your executed command
    You should parse the your $output, instead of $status to know if the remote server is alive or not

    Use this regex to get the value of your lost packages and then decide for the status :

    "#(([0-9]{1,3})% loss)#"
    

Comments are closed.