开发者

select outgoing ip for curl request

开发者 https://www.devze.com 2022-12-22 20:05 出处:网络
I have a server with two different IPs. I need to send odd curl requests from first IP, and even from the second one. How can I select outgoing IP address?

I have a server with two different IPs. I need to send odd curl requests from first IP, and even from the second one. How can I select outgoing IP address?

My PHP script is something like this:

$curlh = curl_init($url);
curl_setopt($curlh, CURLOPT_USERAGENT, 开发者_StackOverflow$uagent);
curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curlh);

How can I do so?


You may want to try setting the CURLOPT_INTERFACE option:

curl_setopt($curlh, CURLOPT_INTERFACE, "xxx.xxx.xxx.xxx");

CURLOPT_INTERFACE: The name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.

From: php Manual: curl_setopt


EDIT: Fixing example, as @Michael Hart pointed out pointed out in the other answer.


Since I can't reply yet, just wanted to add to Daniel Vassallo's answer. While he is correct, his example is not.

CURLOPT_INTERFACE is a constant, and can't be placed within quotes. This could cause a bit of confusion to some who may copy and paste only to find out that it doesn't work. The proper code would be:

curl_setopt($curlh, CURLOPT_INTERFACE, "xxx.xxx.xxx.xxx");

Also, for Linux systems (and I'm sure Windows, but it wont be exactly the same), I feel like pointing out that you don't have to use the IP address. If you know the ethN interface, you can simply use "eth0", "eth1", or "eth0:0" depending on how your network is configured. This may be more preferable, since the code will not be specific to 1 machine, and might fit into a more broad configuration (for example, clusters).

0

精彩评论

暂无评论...
验证码 换一张
取 消