PHP Curl,检索服务器IP地址

时间:2009-09-02 19:50:31

标签: php curl ip-address

我正在使用PHP CURL向服务器发送请求。我需要做什么才能使服务器的响应包含该服务器的IP地址?

6 个答案:

答案 0 :(得分:18)

这个可以完成curl,除了curl请求/响应之外没有其他网络流量的优势。通过curl发出DNS请求以获取IP地址,可以在详细报告中找到。所以:

  • 启用CURLOPT_VERBOSE。
  • 直接CURLOPT_STDERR到a “ php:// temp ”流包装资源。
  • 使用 preg_match_all(),解析 资源的ip字符串内容 地址(ES)。
  • 响应的服务器地址将 在匹配数组的零键 子阵列。
  • 服务器传递的地址 内容(假设成功 请求)可以检索 端()的。任何介入 服务器的地址也将在 这个子阵列,按顺序排列。

演示:

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

答案 1 :(得分:9)

我认为您应该能够通过以下方式从服务器获取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

答案 2 :(得分:3)

我认为没有办法直接从curl获取该IP地址。
但是这样的事情可以解决问题:

首先,执行curl请求,并使用curl_getinfo获取已获取的“真实”URL - 这是因为第一个URL可以重定向到另一个,并且您想要最后一个:< / p>

$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 :(得分:3)

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

这将为您提供与给定主机名相关联的所有IP地址。

答案 4 :(得分:0)

AFAIK你不能“强迫”服务器在响应中向你发送他的IP地址。为什么不直接查找? (检查this question/answers for how to do that from php

答案 5 :(得分:-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