简体   繁体   中英

cURL with PHP, possible to determine the IP address cURL will use?

Is it possible to determine programmatically what IP address cURL is using when connecting to a remote server? I have a shared server that I am using cURL on, and I need to send the IP address as part of the request.

The server that I am talking to requires an authentication string that combines the connection IP address and a rotating passcode (eg my $code = SHA1($_SERVER['SERVER_ADDR'] . $passcode) gets compared on their end with SHA1($_SERVER['REMOTE_ADDR'] . $passcode)). This worked fine when the outgoing connection from cURL was using the same IP as is stored in $_SERVER['SERVER_ADDR'], however the IP address used by cURL is now different and rotating periodically.

You can force the IP that curl uses, as opposed to detecting it.

Use the CURLOPT_INTERFACE option for curl_setopt() - set it to the IP you wish to use.

If you are using a server, such as a cloudserver, with an IP pool - then it is advisable to select the interface to use, if it is important to detect that on the other side, for security reasons.

Personally, I have had to use the feature for card payment data transfers via cURL, when the IP is restricted.

You can do this to get your public IP before you call:

$ch = curl_init('http://whatismyip.org/');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
$myIp = curl_exec($ch);

However:

  • If your public IP sometimes changes between cURL sessions, there is nothing to say that it wont change between the above session and the next one for which you actually need this data.
  • It relies on whatismyip.org (or similar service) actually being running.

There is a web site called whatismyip.com. They have a publically available API that you can use as long as you don't exceed their limit (which is something like five requests per hour??). Won't hurt to give it a shot, eh?

Assuming that curl is always running from the same server, even if it has multiple NICs it shouldn't matter if you tell curl which IP to use.

I would use DaveRandom's trick of getting what IP you are currently using, then set it for the next call using

curl_setopt($ch, CURLOPT_INTERFACE, "XXX.XXX.XXX.XXX");

Assuming the two calls are close enough, there is a very high chance that IP will still be bound to an interface and by setting it you are telling curl to use that one, instead of whichever one the load balancer may want to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM