2009-09-02 152 views

回答

15

這個可以可以用curl來完成,除了curl請求/響應之外沒有其他的網絡流量。 DNS請求通過curl來獲得IP地址,這可以在詳細報告中找到。所以:

  • 打開CURLOPT_VERBOSE。
  • 直接將CURLOPT_STDERR設置爲 「php:// temp」流封裝器資源。
  • 使用preg_match_all(),解析IP地址爲 的資源的字符串內容。
  • 響應服務器地址將 位於匹配數組的零密鑰 子數組中。
  • 服務器遞送 內容(假設成功 請求)的地址可以與 端()檢索。任何干預的 服務器的地址也將在 的子陣列中依次排列。

演示:

$url = 'http://google.com'; 
$wrapper = fopen('php://temp', 'r+'); 
$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_VERBOSE, true); 
curl_setopt($ch, CURLOPT_STDERR, $wrapper); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$result = curl_exec($ch); 
curl_close($ch); 
$ips = get_curl_remote_ips($wrapper); 
fclose($wrapper); 

echo end($ips); // 208.69.36.231 

function get_curl_remote_ips($fp) 
{ 
    rewind($fp); 
    $str = fread($fp, 8192); 
    $regex = '/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/'; 
    if (preg_match_all($regex, $str, $matches)) { 
     return array_unique($matches[0]); // Array([0] => 74.125.45.100 [2] => 208.69.36.231) 
    } else { 
     return false; 
    } 
} 
0

AFAIK您不能'強制'服務器在響應中向您發送他的IP地址。爲什麼不直接查看它? (檢查this question/answers for how to do that from php

+0

服務器由多個正在運行的實例組成,因此我需要確切地找出連接到哪個服務器並響應特定的CURL請求。 – Beier 2009-09-02 20:06:42

3

我不認爲有一種方法可以直接從curl獲取IP地址。
但這樣的事情可以做的伎倆:

首先,做捲曲的請求,並使用curl_getinfo來獲取已被提取的「真實」 URL - 這是因爲,第一URL可以重定向到另一個,並希望最後一個:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "http://www.google.com/"); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$content = curl_exec($ch); 
$real_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); 
curl_close($ch); 
var_dump($real_url); // http://www.google.fr/ 

然後,使用parse_url提取的「主機」的部分從最終網址:

$host = parse_url($real_url, PHP_URL_HOST); 
var_dump($host);  // www.google.fr 

最後,使用gethostbyname噸Ø獲得對應於該主機的IP地址:

$ip = gethostbyname($host); 
var_dump($ip);   // 209.85.227.99 

嗯......
這是一個解決方案^^應該在大多數情況下,我想 - 雖然我不知道你會總是得到如果存在某種負載均衡機制,則爲「正確」結果...

3
echo '<pre>'; 
print_r(gethostbynamel($host)); 
echo '</pre>'; 

這將爲您提供與給定主機名關聯的所有IP地址。

-1

我用這一個

<? 
$hosts = gethostbynamel($hostname); 
if (is_array($hosts)) { 
    echo "Host ".$hostname." resolves to:<br><br>"; 
    foreach ($hosts as $ip) { 
      echo "IP: ".$ip."<br>"; 
    } 
} else { 
    echo "Host ".$hostname." is not tied to any IP."; 
} 
?> 

從這裏:http://php.net/manual/en/function.gethostbynamel.php

3

我想你應該能夠從服務器獲取IP地址:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "http://stackoverflow.com"); 
curl_exec($ch); 
$ip = curl_getinfo($ch,CURLINFO_PRIMARY_IP); 
curl_close($ch); 
echo $ip; // 151.101.129.69