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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23110995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:30:10  来源:igfitidea点击:

How to get Public IP address using PHP?

phpip

提问by Ganesh Babu

I need to get Public IP address of the system using PHP. I tried the following function:

我需要使用 PHP 获取系统的公共 IP 地址。我尝试了以下功能:

function get_client_ip() {
    $ipaddress = '';
    if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    return $ipaddress;
}

But, I got only the localhost IP 127.0.0.1. I am in need of Public IP address. What function is available in PHP to get my Public Ip address which I get from this site:http://www.whatismyip.com/

但是,我只有 localhost IP 127.0.0.1。我需要公共 IP 地址。PHP 中有哪些函数可以获取我从该站点获得的公共 IP 地址:http://www.whatismyip.com/

回答by mikikg

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.

如果您在运行浏览器客户端的同一台机器或本地 LAN 上运行 Web 服务器,则不可能以这种方式获取您的 IP 地址,您将始终获得本地 IP 地址。

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:

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

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

回答by Wit Wikky

Try Using ,

尝试使用,

$_SERVER['REMOTE_ADDR']  

Check this link

检查此链接