我正在使用PHP CURL向服务器发送请求。我需要做什么才能使服务器的响应包含该服务器的IP地址?
使用curl可以完成此操作,其优点是除了curl请求/响应之外没有其他网络流量。Curl会发送DNS请求以获取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;
}
}
我认为您应该能够通过以下方式从服务器获取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
echo '<pre>';
print_r(gethostbynamel($host));
echo '</pre>';
这将为您提供与给定主机名关联的所有IP地址。
我认为不能直接从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
好的...那是一个解决方案^^ 我想它在大多数情况下应该可以工作--尽管如果有某种负载平衡机制,您可能不总是得到“正确”的结果...
我用了这个
<?
$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.";
}
?>