4

I need to specify the source port range for curl.
I don't see any option who let me choose a range for source port in TCP.

Is it possible?

gre_gor
  • 6,669
  • 9
  • 47
  • 52
hotips
  • 2,575
  • 7
  • 42
  • 59

2 Answers2

4

You can use CURLOPT_LOCALPORT and CURLOPT_LOCALPORTRANGE options, which are similar to curl's --local-port command line option.

In the following example curl will try to use source port in range 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;

From the command line one would use:

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

For documentation see: CURLOPT_LOCALPORT and Local port number.

Marián Černý
  • 15,096
  • 4
  • 70
  • 83
1

I think it would be better using fsockopen. I came up many times this worked for me when blocked by firewalls. See: 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";
    }
}

By the way, there is CURLOPT_PORT for CURL, but doesn't work with 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;
Kerem
  • 11,377
  • 5
  • 59
  • 58
  • 2
    CURLOPT_PORT is normally for the distant port : CURLOPT_PORT An alternative port number to connect to. – hotips Feb 19 '13 at 14:53
  • 1
    They are asking to set the port for the connection to connect **from**, not **to**. – gre_gor Oct 11 '22 at 16:01