在Wordpress/PHP中ping一个IP -得到结果


Pinging an IP in Wordpress/PHP - getting results

我试图得到一块脚本,这可以用来测试一个网站是可访问的,并显示此结果。我有一个私人服务器,我也可以用它进行测试。但现在,我们就说谷歌吧。

我已经尝试了很多方法来做这件事:

第一次尝试是使用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);
});

但无论如何这都是正确的

下一个例子是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"); 

但同样,总是显示为活着。我试图访问一个私人服务器,我没有访问权限。这意味着我不能ping这个

欢迎提出任何意见/建议/改进

找到此-完美的工作。很抱歉在这么短的时间内回复,但刚刚试过了,看起来很完美。

http://papermashup.com/php-check-if-your-website-is-up/

你也可以试试

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

$status将只返回已执行命令的状态
您应该解析您的$output,而不是$status,以了解远程服务器是否活动

使用正则表达式获取丢失包的值,然后决定状态:

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