使用PHP使用curl指定源端口范围

时间:2013-02-19 14:01:42

标签: php curl

我需要为curl指定源端口范围。 我没有看到任何让我在TCP中选择源端口范围的选项。

有可能吗?

由于

2 个答案:

答案 0 :(得分:1)

我认为使用fsockopen会更好。当防火墙阻挡时,我多次出现这对我有用。请参阅:http://php.net/fsockopen

$ports = array(80, 81);
foreach ($ports as $port) {
    $fp =@ fsockopen("tcp://127.0.0.1", $port);
    // or fsockopen("www.google.com", $port);
    if ($fp) {
        print "Port $port is open.\n";
        fclose($fp);
    } else {
        print "Port $port is not open.\n";
    }
}

顺便说一下,CURL有CURLOPT_PORT,但不适用于tcp://127.0.0.1;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1");
curl_setopt($ch, CURLOPT_PORT, 80);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$re = curl_exec($ch);
// echo curl_errno($ch);
curl_close($ch);
print $re;

答案 1 :(得分:1)

您可以使用 CURLOPT_LOCALPORTCURLOPT_LOCALPORTRANGE 选项,它们类似于 curl 的 --local-port 命令行选项。

在以下示例中,curl 将尝试使用 6000-7000 范围内的源端口:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_LOCALPORT, 6000);
curl_setopt($ch, CURLOPT_LOCALPORTRANGE, 1000);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;

从命令行可以使用:

curl --local-port 6000-7000 <url>

有关文档,请参阅:CURLOPT_LOCALPORTLocal port number

相关问题