[英]How do I get the external IP address in a Symfony2 controller?
Similar to https://stackoverflow.com/a/9029790/1069375 类似于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? 获取Web服务器的外部/公共IP地址的最Symfony2(内置的)方法是什么?
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. 我正在NAT防火墙后面的localhost上进行编码和测试。 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.
我不希望使用“ 127.0.0.1”作为答案,但是无论Web访问者认为什么,网关都应该将www端口转发到我的开发服务器。 I already do use a dynamic DNS hostname, in case I have to resort to it, but prefer a more portable method.
我已经使用了动态DNS主机名,以防万一我不得不诉诸它,但是我更喜欢一种可移植的方法。
To help avoid going off topic in the comments: 为了避免在评论中出现话题,请执行以下操作:
$_SERVER['REMOTE_ADDR'] // also returns '::1'
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 您可以使用shell_exec从php调用它
You said you do have a dynamic host name. 您说您确实有一个动态主机名。 Use PHP inbuilt function:
使用PHP内置函数:
$serverIp = gethostbyname('your_subdomain.dyndns.org');
This should read your external IP address from your locally configured DNS. 这应该从本地配置的DNS中读取您的外部IP地址。
Update: 更新:
A properly configured server contains the correct information in: 正确配置的服务器在以下位置包含正确的信息:
echo $_SERVER['SERVER_ADDR'];
echo $_SERVER['SERVER_NAME'];
我不想回答我自己的问题,并且很乐意标记一个更好的答案(简短而优雅,并且独立于下面的外部服务器,可能使用网络堆栈,traceroute或某些类似的向导),但是就目前而言,我们需要这么小的任务快速上架或生产的东西,所以:
$CustomerIp = system("curl -s ipv4.icanhazip.com") ; // returns string '93.9.29.389' (length=11)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.