使用PHP自動PING IP,校檢網路連接是否正常!
<?php<br />$server = 'ping kalvin.cn -n 1';<br />$last_line = exec($server, $arr);<br />echo "$last_line"; //最後總結結果<br />print_r($arr); //PING命令詳細資料數組<br />?>
國外一位大師使用Sockets Ping,似乎效率更高:
PHP代碼
<?php<br /> // Checksum calculation function<br /> function icmpChecksum($data)<br /> {<br /> if (strlen($data)%2)<br /> $data .= "/x00"; </p><p> $bit = unpack('n*', $data);<br /> $sum = array_sum($bit); </p><p> while ($sum >> 16)<br /> $sum = ($sum >> 16) + ($sum & 0xffff); </p><p> return pack('n*', ~$sum);<br /> }<br /> // Making the package<br /> $type= "/x08";<br /> $code= "/x00";<br /> $checksum= "/x00/x00";<br /> $identifier = "/x00/x00";<br /> $seqNumber = "/x00/x00";<br /> $data= "Scarface";<br /> $package = $type.$code.$checksum.$identifier.$seqNumber.$data;<br /> $checksum = icmpChecksum($package); // Calculate the checksum<br /> $package = $type.$code.$checksum.$identifier.$seqNumber.$data;<br /> // And off to the sockets<br /> $socket = socket_create(AF_INET, SOCK_RAW, 1);<br /> socket_connect($socket, "www.google.com", null);<br /> // If you're using below PHP 5, see the manual for the microtime_float<br /> // function. Instead of just using the m<br /> // icrotime() function.<br /> $startTime = microtime(true);<br /> socket_send($socket, $package, strLen($package), 0);<br /> if (socket_read($socket, 255)) {<br /> echo round(microtime(true) - $startTime, 4) .' seconds';<br /> }<br /> socket_close($socket);<br />?><br />