获取主机名的IP地址或将主机名转换为php中的ip地址

时间:2014-03-08 23:22:30

标签: php ip ip-address lookup hostname

我有一个脚本使用api来获取ip地址的ip信息。我得到一个问题,获取域或主机名的IP地址或将其转换为IP,我正在寻找一个代码来解决这个问题,所以当访问者来到网站可以磁带或寻找IP和域名并得到ip域名及相关信息,谢谢。

的index.php

<?php

require_once('ipapi.class.php');

if(isset($_GET['ip']))
$rip = $_GET['ip'];
else
$rip = $_REQUEST['REMOTE_ADDR']; // the IP address to query

$query = IPAPI::query("$rip");

echo "\t IP Information: " .$rip. "<br />";
echo "\t ISP: " .$query->isp . "<br />";
echo "\t Organization: " .$query->org . "<br />";
echo "\t City: " .$query->city . "<br />";
echo "\t Region: " .$query->regionName . "<br />";
echo "\t Country: " .$query->country . "<br />"; 

?>

<form name="input" action="#" method="get">
IP: <input type="text" name="ip">
<input type="submit" value="Submit">
</form>

ipapi.class.php

 if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) 
 { 
    $rip = getenv("HTTP_CLIENT_IP"); 
 } 
 else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) 
 { 
    $rip = getenv("HTTP_X_FORWARDED_FOR"); 
 } 
 else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) 
 { 
    $rip = getenv("REMOTE_ADDR"); 
 } 
 else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] &&       strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) 
 { 
    $rip = $_SERVER['REMOTE_ADDR']; 
 } 
 else 
 { 
    $rip = "unknown"; 
 } 

PS:rip = ip我把它命名为rip而不是ip

1 个答案:

答案 0 :(得分:1)

我会使用nslookup将主机名解析为IP。

echo shell_exec('nslookup ' . $example_host_name);