2016年7月5日 星期二

[PHP] 實作 Ping 功能

  function ping($host, $iface=null, $timeout=null) {
     $iface = ($iface===null)?"eth0":$iface;
     $timeout = ($timeout ===null)?1:$timeout;
    /* 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));
    if ( @socket_set_option($socket, SOL_SOCKET, SO_BINDTODEVICE, $iface) === false ) return false;
    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;
    }

Usage:
ping("192.168.1.1"); #[T] 0.0005650520324707
ping("192.168.1.2"); #[F] false

Reference:
[1] http://stackoverflow.com/questions/20467432/php-how-to-ping-a-server-without-system-or-exec

沒有留言:

張貼留言