且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用PHP获取公共IP地址?

更新时间:2023-02-12 18:26:45

如果您在运行浏览器客户端的同一台计算机或本地LAN上运行Web服务器,则无法以此方式获取您的IP地址,您将始终获取本地IP地址。

It is not possible to get Your IP address on that way if you run web server on same machine or local LAN where you run your browser client, you will always get local IP address.

如果您仍希望从PHP脚本获取您的公共地址,则在与您的浏览器客户端在同一网络中运行的* nix服务器上,您可以获得它通过这样的命令:

If You still want to get Your public address from PHP script, on *nix servers which runs in same network as your browser client, you can get it via command like this:

$myPublicIP = trim(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com"));
echo "My public IP: ".$myPublicIP;