views:

269

answers:

1

Full Disclosure: There's a similar question here.

Is there any way I can test if a particular port is open and forwarded properly using PHP? Specifically, how do I go about using a socket to connect to a given user with a given port?

An Example of this is in the 'Custom Port Test' section of WhatsMyIP.org/ports.

+3  A: 

I'm not sure what you mean by being "forwarded properly", but hopefully this example will do the trick:

$host = 'stackoverflow.com';
$ports = array(21, 25, 80, 81, 110, 443, 3306);

foreach ($ports as $port)
{
    $connection = @fsockopen($host, $port);

    if (is_resource($connection))
    {
        echo '<h2>' . $host . ':' . $port . ' ' . '(' . getservbyport($port, 'tcp') . ') is open.</h2>' . "\n";

        fclose($connection);
    }

    else
    {
        echo '<h2>' . $host . ':' . $port . ' is not responding.</h2>' . "\n";
    }
}

Output:

stackoverflow.com:21 is not responding.
stackoverflow.com:25 is not responding.
stackoverflow.com:80 (http) is open.
stackoverflow.com:81 is not responding.
stackoverflow.com:110 is not responding.
stackoverflow.com:443 is not responding.
stackoverflow.com:3306 is not responding.

See http://www.iana.org/assignments/port-numbers for a complete list of port numbers.

Alix Axel
Thanks - this is very similar to what I was expecting to do. When I said 'forwarded properly' I meant that the user has port forwarding enabled on their router for the port I wish to use. I have a multiplayer game which has the option to act as a server. Hence, port forwarding is needed and we would like to have a simple feature that tries to verify that the port is, in fact, forwarded.
Charlie Salts