PHP Curl,检索服务器 IP 地址

标签 php curl ip-address

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

最佳答案

可以通过 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;
    }
}

关于PHP Curl,检索服务器 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1369760/

相关文章:

excel - 如何加速 VBA for Mac 中的 shell 函数

asp.net - 从网络外部访问 aspx 页面的 URL?

php - 什么是 PDO 以及我为什么要使用它?

php - Eloquent 查询 AND OR

http - 使用 curl 调用 golang jsonrpc

curl - 如何使用 curl 多部分表单数据从命令行发布数组字段?

protocols - 如何向我知道 IP 地址的 PC 发送短信?

ruby-on-rails - 现有应用程序中大量模型的 IP 地址记录

php - DQL Query Doctrine 将连接元素 OrderBy 子句放在另一个元素的接合条件的子查询中

javascript - 如何使用 Vuejs 前端框架使用 MySQL/PHP 从服务器获取数据