[英]Get the private ip address at a specific ethernet port in PHP
I have the PHP coe running on a server. 我有在服务器上运行的PHP Coe。 I want the IP address of the local system.
我想要本地系统的IP地址。 This question has been asked before - PHP how to get local IP of system
之前曾有人问过这个问题-PHP如何获取系统的本地IP
When I use any of the solutions mentioned in the above post, I can only get the hostname, not the IP address. 当我使用以上文章中提到的任何解决方案时,我只能获取主机名,而不能获取IP地址。
eg on my machine I have 例如在我的机器上
eth0:10.0.2.15 为eth0:10.0.2.15
eth1:192.168.1.115 的eth1:192.168.1.115
When I run the following code: 当我运行以下代码时:
$localIP = getHostByName(getHostName());
I only get the hostname - localvm
. 我只得到主机名
localvm
。 I want 192.168.1.115
我要
192.168.1.115
Can I get the private ip address? 我可以获取私人IP地址吗? more specifically can I get the IP address at a specific port?
更具体地说,我可以在特定端口获取IP地址吗?
You could get IP address of a specific network port in Linux with something like: 您可以通过以下方式获取Linux中特定网络端口的IP地址:
function getInterfaceIP($interface = 'eth0')
{
$interfaceCommand = "/sbin/ifconfig " . $interface . " | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1 }'";
$output = exec($interfaceCommand);
return $output;
}
echo getInterfaceIP('eth0');
Note that command syntax may differ from OS to OS. 请注意,各操作系统的命令语法可能有所不同。 This example works for Linux.
此示例适用于Linux。 PHP doesn't have any built-in classes to do this.
PHP没有任何内置类可以执行此操作。
You may want to add another command - getting a list of all network interfaces available ('ifconfig -s' provides those). 您可能想要添加另一个命令-获取所有可用网络接口的列表('ifconfig -s'提供了这些接口)。
The accepted answer is correct. 接受的答案是正确的。 However, if someone is working on AWS cloud or Openstack, he can make use of the cloud-init tools (already present) and use the magic IP to retrieve the local ip address as follows:
但是,如果有人正在使用AWS云或Openstack,则可以使用cloud-init工具(已经存在)并使用魔术IP来检索本地IP地址,如下所示:
curl http://169.254.169.254/latest/meta-data/local-ipv4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.