简体   繁体   中英

Getting IP address in php

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...

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.

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.

如果您使用print_r($ _ SERVER),将看到可用的信息,它的外观以及哪些字段为空。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM