![](/img/trans.png)
[英]How can I simplify an IP address using PHP? Trying long2ip(ip2long(address))
[英]PHP: How can I ping an IP address faster
我正在使用exec(“ ping”。$ server-> ip,$ output,$ result); 功能,并且我尝试ping几个ip地址,并且一一ping起来需要太多时间。 是否有更快的方式来ping通它们。
//In my controller
$servers = Server::orderBy('created_at', 'desc')->paginate(10);
foreach ($servers as $server)
{
exec("ping " . $server->ip, $output, $result);
if($result != 0)
{
$server->status = 0;
}
else
{
$server->status = 1;
}
}
所以这是两种方法:
fsockopen()
函数 为什么要花时间使用它,因为每次调用exec
函数时,大部分时间都花在创建外壳程序上,所以这个想法是通过调用system
PHP创建一个迷你程序,该程序在命令行上遍历您的IP地址命令一次,所以这是您需要做的以及随后的解释。 -在doucment_root目录中batch.bat
一个批处理文件batch.bat
,将以下命令放入其中:
set list=172.30.240.56 172.30.240.57 172.30.240.58
(for %%a in (%list%) do (
ping -n 1 %%a
));
您可以通过用white_spaces分隔的IP地址来填充上面的列表。 ping -n 1
只能ping一次,因为您需要速度
Then in your script, it will be as simple as putting:
echo '<pre>';
exec('cmd /c .\batch.bat',$result);
/* $result is an array of lines of the output that you can easily access
look at the result obtained by using print_r($result); below
您甚至可以通过以下命令在PHP脚本中自动创建批处理文件,前提是您具有正确的权限(由于可以运行exec
因此很可能具有此权限):
$servers = Server::orderBy('created_at', 'desc')->paginate(10);
$batch_string=' set list=';
foreach ($servers as $server)
$batch_string.=$server->ip.' ';
$batch_string.= "\n (for %%a in (%list%) do (
ping -n 1 %%a
));";
file_put_contents('batch.bat',$batch_string);
echo '<pre>';
exec('cmd /c .\batch.bat',$result);
我已经在www.google.com
和172.30.240.56
进行了测试,结果如下:(请注意,对于第二个IP地址,ping操作失败)
Array
(
[0] =>
[1] => C:\Batch_File_path>set list=www.google.com 172.30.240.56
[2] =>
[3] => C:\Batch_File_path>(for %a in (www.google.com 172.30.240.56) do (ping -n 1 %a ) )
[4] =>
[5] => C:\Batch_File_path>(ping -n 1 www.google.com )
[6] =>
[7] => Pinging www.google.com [172.217.23.196] with 32 bytes of data:
[8] => Reply from 172.217.23.196: bytes=32 time=84ms TTL=48
[9] =>
[10] => Ping statistics for 172.217.23.196:
[11] => Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
[12] => Approximate round trip times in milli-seconds:
[13] => Minimum = 84ms, Maximum = 84ms, Average = 84ms
[14] =>
[15] => C:\Batch_File_path>(ping -n 1 172.30.240.56 )
[16] =>
[17] => Pinging 172.30.240.56 with 32 bytes of data:
[18] => Request timed out.
[19] =>
[20] => Ping statistics for 172.30.240.56:
[21] => Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
)
fsockopen
命令: 使用套接字,它是PHP内置的,因此维护和检测错误更快,更容易,这是ping Ip地址的示例代码
$fp = fsockopen("www.google.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.google.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.