gpt4 book ai didi

php - 如何找到PHP中的所有监听端口?

转载 作者:行者123 更新时间:2023-12-03 12:04:29 25 4
gpt4 key购买 nike

我正在研究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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com