halfer halfer - 6 months ago 13x
PHP Question

How can I capture the IP used by cURL in Guzzle?

I'm using Goutte (which internally uses Guzzle) for a web scraping project. I'm working on a custom rate limiter, and so am storing all HTTP operations to a database table against an IP so I can check if a call has been made to a host in a recent timeframe.

Currently I'm using

to convert the known hostname to an IP address, but Guzzle would already have done a lookup, and so this may be wasteful. Moreover, hostnames may resolve to more than one IP address (hence the need for
) so the IP I derive myself may not in fact be the one that Guzzle has used (though, at a guess, there could be some caching at the PHP level that would make it likely
returns the correct result).

I've subscribed a plugin to Guzzle, which returns some very interesting data from cURL, in an effort to do this. Sadly, the IP address was not among them. There must be a way to get this though - any ideas?

class HttpLoggerPlugin implements EventSubscriberInterface
public static function getSubscribedEvents()
return array(
'request.complete' => 'onRequestComplete',

* Handles the request complete event (for both success/failed)
* @param \Guzzle\Common\Event $event
public function onRequestComplete(Event $event)
$request = $event['request'];
$host = $request->getHost();

$ip = gethostbyname($host);
$response = $event['response'];
$responseCode = $response ? $response->getStatusCode() : null;
// Try to get cURL data here
echo $response ? print_r($response->getInfo(), true) : null;

This is what the

[url] => http://example.com/page.html
[content_type] => text/html
[http_code] => 200
[header_size] => 228
[request_size] => 149
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 1.209516
[namelookup_time] => 0.559758
[connect_time] => 0.954811
[pretransfer_time] => 0.954916
[size_upload] => 0
[size_download] => 22390
[speed_download] => 18511
[speed_upload] => 0
[download_content_length] => 22390
[upload_content_length] => 0
[starttransfer_time] => 1.056913
[redirect_time] => 0
[certinfo] => Array()
[redirect_url] =>


Use curl_getinfo($ch, CURLINFO_PRIMARY_IP) or look in the "primary_ip" key/value of curl_getinfo($ch).

What's your PHP version? You must be using an old version.