使用 PHP ping 一个 IP 地址并回显结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8030789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:49:18  来源:igfitidea点击:

Pinging an IP address using PHP and echoing the result

phppingshell-exec

提问by Bernard

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.

我有以下功能,到目前为止我还没有工作。我想 ping 一个 IP 地址,然后回显该 IP 是否存在。

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?

有人可以帮助我哪里出错了吗?和/或是否有更好的方法来实现相同的结果?

Many thanks.

非常感谢。

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

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

采纳答案by maraspin

NOTE: Solution below does not work on Windows. On linux exec a "which ping" command from the console, and set command path (of the suggested exec call) accordingly

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

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.

我认为您想检查命令的退出状态,而 shell_exec 为您提供完整输出(由于某种原因,命令输出从命令版本更改为版本可能很危险)。此外,您的变量 $ip 不会在单引号内解释。你必须使用双“”。这可能是您唯一需要解决的问题才能使其正常工作。

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.

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

<?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");

回答by Nilamkumar Patel

This also did not work for me in Wordpress. I also tried -t and -n and other ways, but did not work. I used,

这在 Wordpress 中对我也不起作用。我也尝试过 -t 和 -n 等方式,但没有奏效。我用了,

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"); 

This worked perfectly for me, finally. I referred this from http://www.phpscriptsdaily.com/php/php-ping/Hope this will help

最后,这对我来说非常有效。我从http://www.phpscriptsdaily.com/php/php-ping/引用了这个 希望这会有所帮助

Well I want to modify this as it is working fine on my localhost but not on my live server For live server, I got another thing which now works for both local as well as live.

好吧,我想修改它,因为它在我的本地主机上运行良好,但在我的实时服务器上却没有。

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

Then I show the Server is up for 0 and down for 1.

然后我显示服务器启动为 0,关闭为 1。

This works perfectly for me. I got this from Ping site and return result in PHPThanks @karim79

这对我来说非常有效。我从Ping 站点得到了这个,并在 PHP 中返回结果谢谢@karim79

回答by Jerson Martínez

I have developed the algorithm to work with heterogeneous OS, both Windows and Linux.

我已经开发了与异构操作系统(Windows 和 Linux)一起使用的算法。

Implement the following class:

实现以下类:

<?php

    class CheckDevice {

        public function myOS(){
            if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
                return true;

            return false;
        }

        public function ping($ip_addr){
            if ($this->myOS()){
                if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))
                    return true;
            } else {
                if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
                    return true;
            }

            return false;
        }
    }

    $ip_addr = "151.101.193.69"; #DNS: www.stackoverflow.com

    if ((new CheckDevice())->ping($ip_addr))
        echo "The device exists";
    else 
        echo "The device is not connected";

回答by Tiamiyu Saheed Oluwatosin

i just wrote a very fast solution by combining all knowledge gain above

我刚刚通过结合上述所有知识获得编写了一个非常快速的解决方案

    function pinger($address){
        if(strtolower(PHP_OS)=='winnt'){
            $command = "ping -n 1 $address";
            exec($command, $output, $status);
        }else{
            $command = "ping -c 1 $address";
            exec($command, $output, $status);
        }
        if($status === 0){
            return true;
        }else{
            return false;
        }
    }

回答by Arif Yaacob

this works fine for me..

这对我来说很好用..

$host="127.0.0.1";
$output=shell_exec('ping -n 1 '.$host);

echo "<pre>$output</pre>"; //for viewing the ping result, if not need it just remove it

if (strpos($output, 'out') !== false) {
    echo "Dead";
}
    elseif(strpos($output, 'expired') !== false)
{
    echo "Network Error";
}
    elseif(strpos($output, 'data') !== false)
{
    echo "Alive";
}
else
{
    echo "Unknown Error";
}

回答by Kuldeep

For Windows Use this class

对于 Windows 使用这个类

$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency !== false) {
 print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}

https://github.com/geerlingguy/Ping

https://github.com/geerlingguy/Ping

回答by ChristianG

This works fine with hostname, reverse IP (for internal networks) and IP.

这适用于主机名、反向 IP(用于内部网络)和 IP。

function pingAddress($ip) {
    $ping = exec("ping -n 2 $ip", $output, $status);
    if (strpos($output[2], 'unreachable') !== FALSE) {
        return '<span style="color:#f00;">OFFLINE</span>';
    } else {
        return '<span style="color:green;">ONLINE</span>';
    }
}

echo pingAddress($ip);

回答by bnoeafk

Do check the man pages of your ping command before trying some of these examples out (always good practice anyway). For Ubuntu 16 (for example) the accepted answer doesn't work as the -n 3fails (this isn't the count of packets anymore, -ndenotes not converting the IP address to a hostname).

在尝试其中一些示例之前,请务必检查 ping 命令的手册页(无论如何总是好的做法)。对于 Ubuntu 16(例如),接受的答案在-n 3失败时不起作用(这不再是数据包的计数,-n表示不将 IP 地址转换为主机名)。

Following the request of the OP, a potential alternative function would be as follows:

根据 OP 的要求,潜在的替代功能如下:

function checkPing($ip){
    $ping = trim(`which ping`);
    $ll = exec($ping . '-n -c2 ' . $ip, $output, $retVar);
    if($retVar == 0){
        echo "The IP address, $ip, is alive";
        return true;
    } else {
        echo "The IP address, $ip, is dead";
        return false;
    }
}

回答by Mcile

I use this function :

我使用这个功能:

<?php
function is_ping_address($ip) {
    exec('ping -c1 -w1 '.$ip, $outcome, $status);
    preg_match('/([0-9]+)% packet loss/', $outcome[3], $arr);
    return ( $arr[1] == 100 ) ? false : true;
}