如何使用PHP获取服务器的外部IP? [英] How do I get the external IP of my server using PHP?

查看:81
本文介绍了如何使用PHP获取服务器的外部IP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常听到有人说使用 $ _ SERVER ['SERVER_ADDR'] ,但这会返回我服务器的LAN IP(例如192.168.1.100)。我想要外部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.

推荐答案

只需查询返回您IP地址的主机:

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];

或者,设置一个只回显IP的服务,然后像这样使用:

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

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

只需回显远程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.

请注意,在具有一个或多个 NAT ,您可能有多个外部IP地址。这只会给你一个。

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.

此外,这个解决方案当然取决于可用的远程主机。但是,由于没有广泛实施的标准(没有ISP,只有一些家用路由器实现 UPnP ),没有其他方式来获取您的外部IP地址。即使您可以与本地NAT通信,也无法确定其背后是否有其他NAT。

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.

这篇关于如何使用PHP获取服务器的外部IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆