PHP - ICMP Ping

时间:2018-02-19 16:03:25

标签: php sockets ping php-7 icmp

所以我试图找出如何在PHP的多个系统中可靠地ping几个主机。为此,我决定最好的方法是让PHP进行ICMP ping,以便我不使用exec或类似的。

我目前的解决方案(在谷歌上找到)如下:

function testPing($host, $timeout = 1) {
    /* ICMP ping packet with a pre-calculated checksum */
    $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
    $socket  = socket_create(AF_INET, SOCK_RAW, 1);
    socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
    socket_connect($socket, $host, null);

    $ts = microtime(true);
    socket_send($socket, $package, strLen($package), 0);
    if (socket_read($socket, 255))
        $result = microtime(true) - $ts;
    else
        $result = false;
    socket_close($socket);

    return ($result===false?2:0); // 0 = good, 2 = bad
}

目前会产生Warning: socket_create(): Unable to create socket [10013]: An attempt was made to access a socket in a way forbidden by its access permissions.

如果有人可以解决该错误或更好的ping方法,我会很感激。

0 个答案:

没有答案