php 为 curl 请求选择传出 IP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2425651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
select outgoing ip for curl request
提问by Sergey
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?
我有一个具有两个不同 IP 的服务器。我需要从第一个 IP 甚至第二个 IP 发送奇怪的 curl 请求。如何选择传出IP地址?
My PHP script is something like this:
我的 PHP 脚本是这样的:
$curlh = curl_init($url);
curl_setopt($curlh, CURLOPT_USERAGENT, $uagent);
curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curlh);
How can I do so?
我怎么能这样做?
回答by Daniel Vassallo
You may want to try setting the CURLOPT_INTERFACEoption:
您可能想尝试设置该CURLOPT_INTERFACE选项:
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.
CURLOPT_INTERFACE:要使用的传出网络接口的名称。这可以是接口名称、IP 地址或主机名。
From: php Manual: curl_setopt
EDIT:Fixing example, as @Michael Hart pointed outpointed out in the other answer.
编辑:修复示例,正如@Michael Hart在另一个答案中指出的那样。
回答by Sergey
Since I can't reply yet, just wanted to add to Daniel Vassallo's answer. While he is correct, his example is not.
由于我还不能回复,只是想补充一下 Daniel Vassallo 的回答。虽然他是对的,但他的例子却不是。
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:
CURLOPT_INTERFACE 是一个常量,不能放在引号内。这可能会给一些可能会复制和粘贴却发现它不起作用的人造成一些困惑。正确的代码是:
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).
另外,对于 Linux 系统(我确定是 Windows,但它不会完全相同),我想指出您不必使用 IP 地址。如果您知道 ethN 接口,则可以根据网络的配置简单地使用“eth0”、“eth1”或“eth0:0”。这可能更可取,因为代码不会特定于 1 台机器,并且可能适合更广泛的配置(例如,集群)。

