php 通过 socket 实现一个 ping 的逻辑,可用于检测 ip 端口,上代码 ~
function ping($ip, $port) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_nonblock($socket); socket_connect($socket,$ip, $port); socket_set_block($socket); $read = array($socket); $write = array($socket); $except = array($socket); // 设置超时,这里是关键,不是设置超时的话,程序会被阻塞 // https://www.php.net/manual/zh/function.socket-select.php $status = socket_select($read, $write, $except, 1); return $status; }
Just so so ~