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.
I'm going to add a solution because the others weren't quite right for me because they:
gethostbyname()
(if you think about it, you don't actually have the problem if you know this a priori)$_SERVER
to be set by a web server)ifconfig
output, which can include multiple non-public interfacesThis is what I would suggest:
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$res = socket_connect($sock, '8.8.8.8', 53);
// You might want error checking code here based on the value of $res
socket_getsockname($sock, $addr);
socket_shutdown($sock);
socket_close($sock);
echo $addr; // Ta-da! The IP address you're connecting from
The IP address there is a Google public DNS server. I trust they'll be around and running it for a while. It shouldn't really matter what address you use there as long as its a public IP address that belongs to someone who doesn't mind random connection attempts too much (yourself maybe?).
This is based on an answer I came across when I had a similar problem in Python.
P.S.: I'm not sure how well the above would work if there is sorcery going on between your machine and the internet.