获取客户端与服务器端的IP
2010-10-03
PHP已经提供了相关的方法来获取客户端与服务器端的IP,getenv('REMOTE_ADDR')和变量$_SERVER['REMOTE_ADDR']可以获取客户端的IP,而gethostbyname函数可以通过域名作为参数获取该域名所在的IP地址。
请看下面的程序示例:
<?php
echo "(1)浏览当前页面的用户的 IP 地址为:";
echo $_SERVER['REMOTE_ADDR'];
echo "<br />";
echo "(2)浏览当前页面的用户的 IP 地址为:";
echo getenv('REMOTE_ADDR');
echo "<br />";
echo "(3)主机 www.baidu.com 的 IP 地址为:";
echo gethostbyname('www.nowamagic.net');
?>
程序运行结果:
(1)浏览当前页面的用户的 IP 地址为:127.0.0.1 (2)浏览当前页面的用户的 IP 地址为:127.0.0.1 (3)主机 www.baidu.com 的 IP 地址为:67.20.100.52
获取客户端的 IP 地址,第一个方法是使用了服务器变量 $_SERVER['REMOTE_ADDR'],它正在浏览当前页面用户的 IP 地址,这里的输出结果为 127.0.0.1,因为这是在本地测试,输出的是我本地的环路地址。
第二个是使用函数 getenv('REMOTE_ADDR')。这里使用了函数 getenv : Gets the value of an environment variable(得到各种环境变量的值),返回值:Returns the value of the environment variable varname, or FALSE on an error(失败的话返回 FALSE)。
而获取服务器端的 IP 地址,gethostbyname('www.nowamagic.net')这里使用了函数 gethostbyname : Get the IP address corresponding to a given Internet host name(通过给定的一个主机名字而得到它的 IP 地址),返回值:Returns the IP address of the Internet host specified by hostname or a string containing the unmodified hostname on failure(失败的话返回原样的输入字符主机名)。
注意这里的最后一句,也就是说,如果失败的话,它会将原样输出,例如:
<?php
echo "无效主机 nowamagic 的 IP 地址为:";
echo gethostbyname("nowamagic");
?>
程序运行结果:
无效主机 nowamagic 的 IP 地址为:nowamagic
下面的方法可以将有空格的域名也能输出它的IP地址,主要是用了trim函数。
<?php
// need to trim() because whitespace will confuse the name lookup
$myIP = gethostbyname(trim(' www.nowamagic.net '));
echo $myIP;
?>
下面的函数可以检测互联网上是否存在这个域名:
<?php
//script to see if host exists on Internet
//following up on the above point about host name
//checking and SQL timeouts, run this test script
//and see how long it takes for 2nd call to
//hostname check to fail
//NOTE -- not PHP's fault -- nature of DNS
//A known good dns name (my own)
$nametotest = "fuzzygroup.com";
//Call address test function
testipaddress($nametotest);
//A known bad name (trust me)
$nametotest = "providence.mascot.com";
//Call address test function
testipaddress($nametotest);
//ip address checking function
//for real use should have a return value but example code
function testipaddress ($nametotest) {
$ipaddress = $nametotest;
$ipaddress = gethostbyname($nametotest);
if ($ipaddress == $nametotest) {
echo "No ip address for host, so host "
. "not currently available in DNS and "
. "probably offline for some time<BR>";
}
else {
echo "good hostname, ipaddress = $ipaddress<BR>";
}
}
//Recommended fix for sql applications:
// store url to temporary table
// run second process periodically to
// check urls and update main table
?>

