【问题标题】:How can I capture the IP used by cURL in Guzzle?如何在 Guzzle 中捕获 cURL 使用的 IP?
【发布时间】:2016-04-25 02:21:19
【问题描述】:

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

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

我已经为 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] => 
 )

【问题讨论】:

    标签: php curl guzzle goutte


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢。看起来它是still an issue in 5.4.6,也许它是在 5.5 中添加的?也感谢更新文档 - 刚刚在我的旧错误报告中看到。
    • 在我上面的评论中,我注意到这是now documented。该功能是在 5.4.7 中引入的。
    猜你喜欢
    • 2020-10-23
    • 2023-02-12
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2015-11-22
    • 1970-01-01
    • 2016-06-19
    相关资源
    最近更新 更多