如何在 Guzzle 中捕获 cURL 使用的 IP


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

我正在使用Goutte(内部使用Guzzle)进行网络抓取项目。我正在研究一个自定义速率限制器,因此将所有 HTTP 操作存储到 IP 的数据库表中,以便我可以检查最近一段时间内是否对主机进行了调用。

目前我正在使用gethostbyname将已知主机名转换为IP地址,但是Guzzle已经进行了查找,因此这可能是浪费。此外,主机名可能会解析为多个 IP 地址(因此需要 gethostbynamel ),因此我自己派生的 IP 实际上可能不是 Guzzle 使用的 IP(尽管猜测,PHP 级别可能存在一些缓存,可能会gethostbyname返回正确的结果)。

我已经订阅了一个 Guzzle 插件,它从 cURL 返回一些非常有趣的数据,以努力做到这一点。可悲的是,IP地址不在其中。一定有办法做到这一点 - 有什么想法吗?

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;
    }
}

这是$response->getInfo()返回的内容:

 Array(
        [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] => 
 )

使用curl_getinfo($ch, CURLINFO_PRIMARY_IP)或查看curl_getinfo($ch)"primary_ip"键/值。

你的 PHP 版本是什么?您必须使用旧版本。