Wige
Wige

Reputation: 3918

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.

Upvotes: 4

Views: 11581

Answers (4)

DaveRandom
DaveRandom

Reputation: 88647

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.

Upvotes: 3

Drazisil
Drazisil

Reputation: 3343

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.

Upvotes: 1

user946954
user946954

Reputation: 45

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?

Upvotes: 1

Orbling
Orbling

Reputation: 20602

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.

Upvotes: 3

Related Questions