PHP Curl,检索服务器IP地址

Bei*_*ier 8 php curl ip-address

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

GZi*_*ipp 19

可以通过卷曲来完成,除了卷曲请求/响应之外没有其他网络流量的优点.通过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;
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 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
Run Code Online (Sandbox Code Playgroud)