简体   繁体   中英

Get the private ip address at a specific ethernet port in PHP

I have the PHP coe running on a server. I want the IP address of the local system. This question has been asked before - PHP how to get local IP of system

When I use any of the solutions mentioned in the above post, I can only get the hostname, not the IP address.

eg on my machine I have

eth0:10.0.2.15
eth1:192.168.1.115

When I run the following code:

$localIP = getHostByName(getHostName());

I only get the hostname - localvm . I want 192.168.1.115

Can I get the private ip address? more specifically can I get the IP address at a specific port?

You could get IP address of a specific network port in Linux with something like:

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. PHP doesn't have any built-in classes to do this.

You may want to add another command - getting a list of all network interfaces available ('ifconfig -s' provides those).

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:

curl http://169.254.169.254/latest/meta-data/local-ipv4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM