我正在开发 PHP 应用程序,我需要找出所有具有监听状态的端口。
注意:fsockopen()
仅适用于已建立的连接。
最佳答案
这将为您提供本地 IP 地址的监听端口列表。我正在使用system()这里和 netstat 命令,确保您的 PHP 安装可以使用该函数,并首先从终端测试 netstat 的输出,看看它是否有效。
编辑:添加了对 Windows 和 Linux 的支持。
function get_listening_ports()
{
$output = array();
$options = ( strtolower( trim( @PHP_OS ) ) === 'linux' ) ? '-atn' : '-an';
ob_start();
system( 'netstat '.$options );
foreach( explode( "\n", ob_get_clean() ) as $line )
{
$line = trim( preg_replace( '/\s\s+/', ' ', $line ) );
$parts = explode( ' ', $line );
if( count( $parts ) > 3 )
{
$state = strtolower( array_pop( $parts ) );
$foreign = array_pop( $parts );
$local = array_pop( $parts );
if( !empty( $state ) && !empty( $local ) )
{
$final = explode( ':', $local );
$port = array_pop( $final );
if( is_numeric( $port ) )
{
$output[ $state ][ $port ] = $port;
}
}
}
}
return $output;
}
输出:
Array
(
[listen] => Array
(
[445] => 445
[9091] => 9091
[3306] => 3306
[587] => 587
[11211] => 11211
[139] => 139
[80] => 80
[3312] => 3312
[51413] => 51413
[22] => 22
[631] => 631
[25] => 25
[443] => 443
[993] => 993
[143] => 143
)
[syn_recv] => Array
(
[80] => 80
)
[time_wait] => Array
(
[80] => 80
[51413] => 51413
)
[established] => Array
(
[22] => 22
[9091] => 9091
[80] => 80
[3306] => 3306
)
[fin_wait2] => Array
(
[80] => 80
)
)
关于php - PHP中如何查找所有监听的端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34815425/