试用php的ping命令

使用PHP自动PING IP,校检网络连接是否正常!

 

 

  1. <?php      
  2. $server = 'ping kalvin.cn -n 1';      
  3. $last_line = exec($server, $arr);      
  4. echo "$last_line"; //最后总结结果      
  5. print_r($arr); //PING命令详细数据数组      
  6. ?>  

 

 

国外一位大师使用Sockets Ping,似乎效率更高:

PHP代码

 

  1. <?php      
  2.     // Checksum calculation function      
  3.     function icmpChecksum($data)      
  4.     {      
  5.     if (strlen($data)%2)      
  6.     $data .= "/x00";      
  7.           
  8.     $bit = unpack('n*', $data);      
  9.     $sum = array_sum($bit);      
  10.           
  11.     while ($sum >> 16)      
  12.     $sum = ($sum >> 16) + ($sum & 0xffff);      
  13.           
  14.     return pack('n*', ~$sum);      
  15.     }      
  16.     // Making the package      
  17.     $type= "/x08";      
  18.     $code= "/x00";      
  19.     $checksum= "/x00/x00";      
  20.     $identifier = "/x00/x00";      
  21.     $seqNumber = "/x00/x00";      
  22.     $data= "Scarface";      
  23.     $package = $type.$code.$checksum.$identifier.$seqNumber.$data;      
  24.     $checksum = icmpChecksum($package); // Calculate the checksum      
  25.     $package = $type.$code.$checksum.$identifier.$seqNumber.$data;      
  26.     // And off to the sockets      
  27.     $socket = socket_create(AF_INET, SOCK_RAW, 1);      
  28.     socket_connect($socket, "www.google.com", null);      
  29.     // If you're using below PHP 5, see the manual for the microtime_float      
  30.     // function. Instead of just using the m      
  31.     //     icrotime() function.      
  32.     $startTime = microtime(true);      
  33.     socket_send($socket, $package, strLen($package), 0);      
  34.     if (socket_read($socket, 255)) {      
  35.     echo round(microtime(true) - $startTime, 4) .' seconds';      
  36.     }      
  37.     socket_close($socket);      
  38. ?>     

 转自http://blog.csdn.net/gumanren/article/details/5752394

posted on 2015-03-25 09:29  liuwenbohhh  阅读(1058)  评论(0编辑  收藏  举报