Question

Similar to https://stackoverflow.com/a/9029790/1069375

What is the most Symfony2 (built-in?) way to get the external/public IP address of the web server?

Eg. is there anything close to this?

$this->container->get('request')->getClientIp(); // returns string '::1' (length=3)

NOTE

I am coding and testing on localhost, behind a NAT firewall. I don't want "127.0.0.1" as an answer, but whatever web visitors would perceive should the gateway forward the www ports to my dev server. I already do use a dynamic DNS hostname, in case I have to resort to it, but prefer a more portable method.

To help avoid going off topic in the comments:

 $_SERVER['REMOTE_ADDR'] // also returns '::1'
Was it helpful?

Solution 3

I hate to answer my own question, and will gladly mark a better answer (short and elegant and independent of outside servers unlike below, maybe using the network stack, traceroute or some such wizardry), but for now for a task this small we needed something quick for staging or production, so:

  $CustomerIp =  system("curl -s ipv4.icanhazip.com") ;  // returns string '93.9.29.389' (length=11)

OTHER TIPS

You have two possibilities. The first one is the simple one, ask some third parties server:

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

And the other one, is to parse your server config, like:

/sbin/ifconfig |grep -B1 "inet addr" |awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }' |awk -F: '{ print $1 ": " $3 }'

you can call it from php using shell_exec

You said you do have a dynamic host name. Use PHP inbuilt function:

$serverIp = gethostbyname('your_subdomain.dyndns.org');

This should read your external IP address from your locally configured DNS.

Update:

A properly configured server contains the correct information in:

echo $_SERVER['SERVER_ADDR'];
echo $_SERVER['SERVER_NAME'];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top