César Nontol César Nontol - 9 months ago 43
PHP Question

How to get the Public IP

I'm trying to get the Public IP of someone that use the form of the page I do.

I don't know with which programming language would do that. I was reading on the web and I found some:

// PHP Code

This outputs: (Local IP).

Then I found this too:

// PHP Code
$externalContent = file_get_contents('http://checkip.dyndns.com/');
preg_match('/\b(?:\d{1,3}\.){3}\d{1,3}\b/', $externalContent, $m);
$externalIp = $m[0];

This outputs the correct IP (Public IP), but that needs to use other web page (http://checkip.dyndns.com/).

I wonder How do the pages like that get the Public IP?. I am looking for a way to get it without need to use other web page. Thanks.

Answer Source

The $_SERVER["REMOTE_ADDR"] should work fine for what you are trying to do here. The reason you are getting is because you are running this in a local environment.

If you put this script on a live webserver and I access it, you will get the same IP from $_SERVER["REMOTE_ADDR"] as I get when I check whatismyip

And anyhow, having the server call:

$externalContent = file_get_contents('http://checkip.dyndns.com/');

will only get you successful in returning your servers IP address, not the visitors.