JDogg1329
JDogg1329

Reputation: 1

Checking whether or not a port is reachable with PHP

I'm trying to check whether ports on my server are open, I've got some php to do this

<?php    
$host = 'xxxxxxxxxxxxxxxxxxx';
    $ports = array(xxxxxx);

    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";
        }
    }
    ?>

Which outputs the following:

domain.zapto.org:80 (http) is open. domain.zapto.org:8090 is not. responding. domain.zapto.org:34134 is not responding.

But if I go to domain.zapto.org:34134 it works fine.... So it is reachable, but why is it saying it isn't? Any ideas? Thanks guys.

Upvotes: 0

Views: 377

Answers (1)

xzag
xzag

Reputation: 604

Add basic debugging to your code by supplying fsockopen function additional parameters (See manual)

$host = 'theofilaktoshouse.zapto.org';
$ports = array(80, 8090, 34134);

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

    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. Error {$errno}: {$errstr} </h2>" . "\n";
    }
}

Reason why it may not work is the traffic rules set up by your hoster. They can easily ban outgoing connections to ports other than 80

Upvotes: 1

Related Questions