aak
aak

Reputation: 127

How to find all the listening port in PHP?

I am working on PHP application and I need to find out all the ports that have listening status.

Note: fsockopen() works only for established connection.

Upvotes: 2

Views: 4182

Answers (1)

Rainner
Rainner

Reputation: 589

This should give you a list of listening ports for local ip addresses. I'm using system() here, and the netstat command, make sure your PHP installation can use that function and test the output of netstat from the terminal first to see if it works.

EDIT: Added support for both windows and 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;
}

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
        )

)

Upvotes: 2

Related Questions