PHP Curl,获取服务器IP地址

9

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

6个回答

22

使用curl可以完成此操作,其优点是除了curl请求/响应之外没有其他网络流量。Curl会发送DNS请求以获取IP地址,这些地址可以在详细报告中找到。所以:

  • 打开CURLOPT_VERBOSE。
  • 将CURLOPT_STDERR直接定向到“php://temp”流包装资源。
  • 使用preg_match_all()解析资源的字符串内容以获取IP地址。
  • 响应服务器的地址将在匹配数组的零键子数组中。
  • 可以使用end()获取传递内容的服务器的地址(假设请求成功)。任何介于服务器和目标地址之间的服务器地址也将按顺序出现在子数组中。

示例:

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

12

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

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

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


3

我认为不能直接从curl中获取IP地址。


但是可以通过以下方式实现:


首先,进行curl请求,并使用curl_getinfo获取已抓取的“真实”URL -- 这是因为第一个URL可能会重定向到另一个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

好的...那是一个解决方案^^ 我想它在大多数情况下应该可以工作--尽管如果有某种负载平衡机制,您可能不总是得到“正确”的结果...


0
据我所知,你无法“强制”服务器在响应中向你发送它的IP地址。为什么不直接查找呢?(从php中查找方法请参阅此问题/答案

服务器由多个运行实例组成,因此我需要确定我连接到了哪个服务器,并对特定的CURL请求进行响应。 - Beier

-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/zh/function.gethostbynamel.php


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接