使用PHP ping IP地址并回显结果 [英] Pinging an IP address using PHP and echoing the result

查看:213
本文介绍了使用PHP ping IP地址并回显结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能,到目前为止我还无法使用.我想ping一个IP地址,然后回显该IP是否有效.

I have the following function that I doesn't work so far. I would like to ping an IP address and then to echo whether the IP is alive or not.

function pingAddress($ip){
    $pingresult = shell_exec("start /b ping $ip -n 1");
    $dead = "Request timed out.";
    $deadoralive = strpos($dead, $pingresult);

    if ($deadoralive == false){
        echo "The IP address, $ip, is dead";
    } else {
        echo "The IP address, $ip, is alive";
    }

}

当我使用示例调用此函数时:

When I call this function using the example:

pingAddress("127.0.0.1")

回声结果始终为死"-无论如何.

The echo result is always 'dead' - no matter what.

有人可以帮我解决我的问题吗? 和/或是否有更好的方法可以达到相同的结果?

Could someone please help me where I'm going wrong? And/OR is there a better method of doing this with the same result?

非常感谢.

更新:修改了代码以包括双引号,但仍然得到相同(不正确)的结果.

Update: Have amended code to include the double quotes but still getting the same (incorrect) results.

推荐答案

注意:以下解决方案在Windows上不起作用.在linux exec上,从控制台执行"ping ping"命令,并相应地设置(建议的exec调用的)命令路径

我认为您想检查命令的退出状态,而shell_exec为您提供完整的输出(出于某种原因,命令输出在命令版本之间更改可能会很危险).此外,您的变量$ ip不会在单引号内解释.您必须使用双引号".这可能是您需要修复的唯一东西,以使其正常工作.

I think you want to check the exit status of the command, whereas shell_exec gives you full output (might be dangerous shall command output change from command version to version. for some reason). Moreover your variable $ip is not interpreted within single quotes. You'd have to use double ones "". That might be the only thing you need to fix in order to make it work.

但是我认为以下代码可能更便携".恕我直言,实际上最好是捕获退出状态,而不是尝试解析结果字符串.恕我直言,最好指定ping命令的完整路径.

But I think following code can be more "portable". IMHO it is in fact better to catch the exit status, rather than trying to parse result string. IMHO it's also better to specify full path to ping command.

<?php
function pingAddress($ip) {
    $pingresult = exec("/bin/ping -n 3 $ip", $outcome, $status);
    if (0 == $status) {
        $status = "alive";
    } else {
        $status = "dead";
    }
    echo "The IP address, $ip, is  ".$status;
}

pingAddress("127.0.0.1");

这篇关于使用PHP ping IP地址并回显结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆