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

标签 php sockets networking port

我正在开发 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/

相关文章:

php - 如何在 MySql 查询方法中写入开始日期和开始日期?

java - 使用Java获取当前机器的IP地址

java - 套接字中的 UnknownHostException

php - 使用 PHP 从 Nagios 获取(原始)数据(?)

php - Laravel 在 Controller 中划分并在 Blade 中显示

使用 libcurl 捕获 RTSP 流

networking - Powershell 在当前服务器上创建共享 - 授予用户/组权限

windows - Windows : ssh_exchange_identification 中的 Vagrant ssh

ios - 通知 iOS 应用程序更新其内容

php - 是否存在 PHP 每功能(或每任务)性能/基准引用?