Get location form a users IP address

2019-03-01 04:11发布

问题:

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.

回答1:

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.



标签: php ip