2013-10-23 16 views
1

我正在使用Goutte(內部使用Guzzle)進行網頁抓取項目。我正在處理自定義速率限制器,因此我將所有HTTP操作都存儲到數據庫表中,以便檢查是否在最近的時間範圍內調用了主機。如何在Guzzle中捕獲cURL使用的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] => 
) 

回答

1

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

什麼是您的PHP版本?您必須使用舊版本。

+0

謝謝。看起來它[仍然是5.4.6中的問題](https://bugs.php.net/bug.php?id=62912),也許它在5.5中添加了?還要感謝您更新文檔 - 在我的舊bug報告中看到了這一點。 – halfer

+0

除了上面我的評論,我注意到這是[現在記錄](https://php.net/manual/en/function.curl-getinfo.php)。該功能在5.4.7中介紹。 – halfer