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;
}
}
答
我不认为有一种方法可以直接从curl获取IP地址。
但这样的事情可以做的伎俩:
首先,做卷曲的请求,并使用curl_getinfo
来获取已被提取的“真实” 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
提取的“主机”的部分从最终网址:
$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
嗯......
这是一个解决方案^^应该在大多数情况下,我想 - 虽然我不知道你会总是得到如果存在某种负载均衡机制,则为“正确”结果...
答
echo '<pre>';
print_r(gethostbynamel($host));
echo '</pre>';
这将为您提供与给定主机名关联的所有IP地址。
答
我用这一个
<?
$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.";
}
?>
答
我想你应该能够从服务器获取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
服务器由多个正在运行的实例组成,因此我需要确切地找出连接到哪个服务器并响应特定的CURL请求。 – Beier 2009-09-02 20:06:42