Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

portforwarding - Test if port open and forwarded using PHP

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>' . "
";

        fclose($connection);
    }

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...