[英]PHP Curl, retrieving Server IP Address
我正在使用PHP CURL向服務器發送請求。 我需要做什么才能使服務器的響應包含該服務器的IP地址?
這可以通過卷曲來完成,除了卷曲請求/響應之外沒有其他網絡流量的優點。 通過curl發出DNS請求以獲取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;
}
}
我認為您應該能夠從服務器獲取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
我認為沒有辦法直接從curl獲取該IP地址。
但是這樣的事情可以解決這個問題:
首先,執行curl請求,並使用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
從該最終URL中提取“host”部分:
$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
好...
這是一個解決方案^^它應該適用於大多數情況,我想 - 雖然我不確定如果存在某種負載平衡機制,你總會得到“正確”的結果......
echo '<pre>';
print_r(gethostbynamel($host));
echo '</pre>';
這將為您提供與給定主機名關聯的所有IP地址。
AFAIK你不能“強迫”服務器在響應中向你發送他的IP地址。 為什么不直接查找? (檢查這個問題/答案,如何從PHP做到這一點 )
我用過這個
<?
$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.";
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.