1

I am trying to get a location from a uses IP address. There is a lot of topics on how to do this. I really like this one, it works and is very clear. The IP address used in the example finds the location somewhere in germany, but when I use my IP address (192.168.0.7) everything comes back as unknown. When the site is only online I wouldn't be using my IP address I would be finding the users IP address using PHP.

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'];

        }
$ip = '192.168.0.7'; //replace with my IP address

I have also came across this site which finds my IP address, which is quite accurate except the numbers are different. 2.126.219.101

Is there a way I can test what I have on localhost to obtain my IP address using the above method or is there something wrong with my IP address.

Community
  • 1
  • 1
Paul Ledger
  • 1,125
  • 4
  • 21
  • 46
  • 1
    192.168.* is a _private_ IP address. You can't geolocate that, makes no sense (there are probably thousands of computers all over the world with that exact IP right now). Use public IP addresses. – Mat Dec 01 '13 at 11:23
  • so in theory 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']; } will work online – Paul Ledger Dec 01 '13 at 11:26

1 Answers1

2

192.168.0.7 is your private IP address. It is only valid within your local (home,work...) network. Because it is only valid inside your local network, it cannot be used for location. In fact, there are probably millions of other computers in the world right now that also have this private IP address within their own networks.

2.126.219.101 is your public IP address. As far any machine outside of your local network is concerned, that is your IP address. It can be used to give an indication of location.

joews
  • 29,767
  • 10
  • 79
  • 91
  • That makes sense but its now very accurate. For example I live in the North of England but I bought my lap top in London. My public IP address returns as London not my actual location – Paul Ledger Dec 01 '13 at 11:29
  • I'm afraid that is the nature of IP location - it isn't always accurate. Your ISP probably allocates your IP address from a pool which serves a large part of the country, not just your local area. – joews Dec 01 '13 at 11:31
  • A better way would be to use javascript and display the data after the pages loads then. It would be a lot more accurate – Paul Ledger Dec 01 '13 at 11:38