PHP Curl,检索服务器IP地址 [英] PHP Curl, retrieving Server IP Address

查看:173
本文介绍了PHP Curl,检索服务器IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHP CURL向服务器发送请求。

I'm using PHP CURL to send a request to a server. What do I need to do so the response from server will include that server's IP address?

推荐答案

可以

This can be done with curl, with the advantage of having no other network traffic besides the curl request/response. DNS requests are made by curl to get the ip addresses, which can be found in the verbose report. So:


  • 开启CURLOPT_VERBOSE。

  • 将CURLOPT_STDERR直接指向
    > 使用 preg_match_all()解析
    资源的字符串内容
    地址

  • 响应的服务器地址将
    存储在匹配数组的零键
    子阵列中。

  • 提供
    内容的服务器的地址(假设成功的
    请求)可以用
    end()检索。

  • Turn on CURLOPT_VERBOSE.
  • Direct CURLOPT_STDERR to a "php://temp" stream wrapper resource.
  • Using preg_match_all(), parse the resource's string content for the ip address(es).
  • The responding server addresses will be in the match array's zero-key subarray.
  • The address of the server delivering the content (assuming a successful request) can be retrieved with end(). Any intervening servers' addresses will also be in the subarray, in order.

演示:

$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地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆