【问题标题】:Is there a way to check for available ports in range in PHP?有没有办法检查 PHP 范围内的可用端口?
【发布时间】:2021-11-16 09:58:39
【问题描述】:

我目前正在尝试弄清楚如何检查 53000-53050 范围内的所有可用端口。但是,我无法弄清楚这一点。我已经尝试了多个响应,在我的情况下,我要么使用 localhost 作为主机,要么收到一条错误消息“(无法建立连接,因为目标机器主动拒绝它。)”,或者没有在全部。有什么想法吗?

谢谢。

【问题讨论】:

  • 这有什么意义?编译可用端口列表后,可能会使用其中一个端口,而列表将是错误的。
  • 如果您发布至少一种您尝试过的解决方案,您更有可能收到回复 - 该网站的许多用户会回避没有代码的问题,因为它们通常是简单的“代码请求” .'

标签: php range port


【解决方案1】:

短解:

$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;
    }
}

【讨论】:

    【解决方案2】:

    对于 PHP,请使用 fsockopen 和 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/>";
            }
        }
    }
    ?>
    

    【讨论】:

    • 你好,我试过了,都无法访问。我正在尝试做的是启动服务器并使用 PHP 获取可用端口。 PHP 将检查 53000-53050 范围内的第一个可用端口并使用该端口。
    • 如果扫描结果无法访问,则表示它可用,您可以在该端口启动服务器(请在防火墙设置中允许该端口的连接)
    • 哦,好吧。抱歉,我对 PHP 很陌生,只了解基本的东西。谢谢!
    • 不客气。祝你有美好的一天
    猜你喜欢
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多