Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the external IP of my server using PHP?

Tags:

php

ip

I often hear people say to use "$_SERVER['SERVER_ADDR']", but that returns the LAN IP of my server (e.g. 192.168.1.100). I want the external IP.

like image 564
Leo Jiang Avatar asked Oct 26 '11 21:10

Leo Jiang


People also ask

How do I find my server IP in PHP?

In order to obtain the IP address of the server one can use ['SERVER_ADDR'], it returns the IP address of the server under the current script is executing. Another method is using the ['REMOTE_ADDR'] in the $_SERVER array.

How can I get public IP in PHP?

The simplest way to collect the visitor IP address in PHP is the REMOTE_ADDR. Pass the 'REMOTE_ADDR' in PHP $_SERVER variable. It will return the IP address of the visitor who is currently viewing the webpage.

How do I find internal and external IP address?

Here are the instructions for windows:Type cmd and press enter. In this new windows type ipconfig and press enter. You will see a bit more information than you may want what your looking for is IPv4 Address. The number across from that is your local IP address.


2 Answers

There is NO way to get your underlying IP Address that has been designated by your ISP via conventional PHP if you are using a router. A way to get the external IP is to find a service that will obtain it for you and echo the address back to you. I found a handy service which does just that. http://ipecho.net/

You can use:

$realIP = file_get_contents("http://ipecho.net/plain"); 
like image 129
Ben Avatar answered Sep 20 '22 18:09

Ben


Just query a host that returns your IP address:

$externalContent = file_get_contents('http://checkip.dyndns.com/'); preg_match('/Current IP Address: \[?([:.0-9a-fA-F]+)\]?/', $externalContent, $m); $externalIp = $m[1]; 

or, set up a service that simply echoes just the IP, and use it like this:

$externalIp = file_get_contents('http://yourdomain.example/ip/'); 

Set up the service yourself by simply echoing the remote IP address, or pay someone to host it. Do not use somebody else's server without permission. Previously, this answer linked to a service of mine that's now being hit multiple times a second.

Note that in an IP network with one or more NATs, you may have multiple external IP addresses. This will give you just one of them.

Also, this solution of course depends on the remote host being available. However, since there is no widely implemented standard (no ISP and only some home routers implement UPnP), there is no other way to get your external IP address. Even if you could talk to your local NAT, you couldn't be sure that there isn't another NAT behind it.

like image 44
phihag Avatar answered Sep 22 '22 18:09

phihag