Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if anything is listening in a port in PHP

Tags:

php

port

I want to use PHP to check if anything is listening to localhost:81, to ensure that is available for a PHP built in server to run on.

i.e. I want to check if the following would run properly php -S localhost:81.

Now if something is already listening on port 81 (e.g. Apache), this will of course cause problems.

I read the following: How can I check if ports 465 and 587 are open with PHP? and the solution did not seem to work.

i.e.:

$fp = fsockopen('localhost', '81', $errno, $errstr, 5);
var_dump($fp); // returns false
if (!$fp) {
    // port is closed or blocked
    echo "CLOSED!";
    return false;
} else {
    // port is open and available
    echo "OPEN!";
    fclose($fp);
    return true;
}

Unfortunately the above keeps returning "CLOSED!" even though its not.

I also get the following error message:

PHP Warning:  fsockopen(): unable to connect to localhost:81 (Connection refused)

How do I solve my problem?

Is there any alternatives?

like image 408
Yahya Uddin Avatar asked Sep 23 '16 09:09

Yahya Uddin


1 Answers

You should actually check to see if fsockopen() has returned a resource:

$connection = @fsockopen('localhost', '81');

if (is_resource($connection))
{
    echo 'Open!';
    fclose($connection);
    return true;
}
else
{
    echo 'Closed / not responding. :(';
    return false;
}
like image 84
BenM Avatar answered Sep 19 '22 06:09

BenM