I am this code to get the IP address on my locolhost and I get
::1
result
code is:
function ip()
{
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
echo ip();
where is error?
Actually, I want to get country & city name after I get IP.开发者_开发问答.. Any other solution?
Thanks
::1 is shorthand for localhost, using IPv6 terminology, so it is working. Try connecting using your hostname, and you should see the address change to be more obviously an address...
As @Roland writes it is an IPv6 address. If you don't intend on using IPv6 in your application then you should tell your web server to stop listening on IPv6 ports. When you send a request the client will try IPv6 first if it doesn't work then it will fall back to IPv4 and you should get the much more familiar looking 127.0.0.1.
You could use the following:
$server_address = $_SERVER['SERVER_ADDR'];
$port_used = $_SERVER['SERVER_PORT'];
$ip_address = $_SERVER['REMOTE_ADDR'];
// on my test machine this gives the following results:
$server_address = 127.0.0.1
$port_used = 80
$ip_address = 127.0.0.1
Edited: to include the geo-location aspect of the question, that I hadn't noticed 'til after I submitted the original answer.
Rather than repeat answers found elsewhere, I'll first link to this (well-answered) SO question: google-geolocation-api-library, and then to the Google results page for the search terms geolocation php site:stackoverflow.com, which links to many other -probably relevant- answers that might better address your questions than I'm able.
If you print_r($_SERVER) you will see what information is available, what it looks like, and what fields might be empty.
精彩评论