php PHP显示服务器IP地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4420468/
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 13:01:14  来源:igfitidea点击:

PHP display server IP Address

phpip-addressip

提问by Ethan Mick

I'm working on a website, and one of the things I would like to do is display MY IP address to users. The website is made with CodeIgniter, so I was looking to find my server IP with PHP. The IP address may change (it's a roamer), so I'd like to find it dynamically, not just hard code it. I tried this:

我在一个网站上工作,我想做的一件事是向用户显示我的 IP 地址。该网站是用 CodeIgniter 制作的,所以我想用 PHP 找到我的服务器 IP。IP 地址可能会更改(它是漫游器),因此我想动态查找它,而不仅仅是对其进行硬编码。我试过这个:

$data['hostname'] = NULL;
$data['ip'] = NULL;
$var = gethostname();
if ($var === FALSE) {
  $var = NULL;
} else {
  $data['hostname'] = $var;
  $data['ip']   = gethostbyname($var);
}

However, instead of giving me the Hostname and the IP, I got: "Moria" and "127.0.1.1". Not quite what I am looking for. Rather, it should say "Moria.student.rit.edu" for the Hostname, and the IP address. Any help?

但是,我没有给我主机名和 IP,而是得到:“Moria”和“127.0.1.1”。不完全是我正在寻找的。相反,它应该为主机名和 IP 地址显示“Moria.student.rit.edu”。有什么帮助吗?

回答by Matthew

Try $_SERVER['SERVER_ADDR']. It will be the IP address that the server is listening on. You can use DNS functions (e.g., gethostbyaddr()) to get the host name.

试试$_SERVER['SERVER_ADDR']。它将是服务器正在侦听的 IP 地址。您可以使用 DNS 功能(例如,gethostbyaddr())来获取主机名。

See http://www.php.net/manual/en/reserved.variables.server.php.

请参阅http://www.php.net/manual/en/reserved.variables.server.php

回答by ravi

for server ip address $_SERVER['SERVER_ADDR'];

对于服务器 ip 地址 $_SERVER['SERVER_ADDR'];

and for server port $_SERVER['SERVER_PORT'];

和服务器端口 $_SERVER['SERVER_PORT'];

回答by jmurray

If your laravel application is running on an internal server, you can use the following to get the external address of the server:

如果您的 Laravel 应用程序运行在内部服务器上,您可以使用以下命令来获取服务器的外部地址:

 $external_ip = exec('curl http://ipecho.net/plain; echo');