Home > Blockchain >  Is there a way to check for available ports in range in PHP?
Is there a way to check for available ports in range in PHP?

Time:09-23

I'm currently trying to figure out how to check for all available ports in the range 53000-53050. However, I cannot figure this out. I've tried out multiple responses, and in my case, I either got an error stating "(No connection could be made because the target machine actively refused it.)" using localhost as the host, or didn't load the page at all. Any ideas?

Thanks.

CodePudding user response:

Short solution:

$host = 'stackoverflow.com';

$start = 53000;
$end = 53050;

for($port = $start; $port <= $end; $port  )
{
    $connection = @fsockopen($host, $port);

    if (is_resource($connection)) {
        echo $host . ':' . $port . ' ' . '(' . getservbyport($port, 'tcp') . ') is open.' . PHP_EOL;
        fclose($connection);
    }  else {
        echo $host . ':' . $port . ' is not responding.' . PHP_EOL;
    }
}

CodePudding user response:

For PHP, please use fsockopen and getservbyport

<form method="post" >
    Domain/IP: 
    <input type="text" name="domain" /> 
    <input type="submit" value="Scan" />
</form>
<br />
 
<?php
if(!empty($_POST['domain'])) {    
    //list of port numbers to scan

//   $ports = array(21, 22, 23, 25, 53, 80, 110, 1433, 3306);

/////////// Use this block to set start port and end port 

$ports=array();
$i=53000;

while ($i <=53050){
array_push($ports, $i);
$i  ;
}

/////////// end block

    
    $results = array();
    foreach($ports as $port) {
        if($pf = @fsockopen($_POST['domain'], $port, $err, $err_string, 1)) {
            $results[$port] = true;
            fclose($pf);
        } else {
            $results[$port] = false;
        }
    }
 
    foreach($results as $port=>$val)    {
        $prot = getservbyport($port,"tcp");
                echo "Port $port ($prot): ";
        if($val) {
            echo "<span style=\"color:green\">OK</span><br/>";
        }
        else {
            echo "<span style=\"color:red\">Inaccessible</span><br/>";
        }
    }
}
?>
  • Related