2

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.

e.g. 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?

Community
  • 1
  • 1
kosta
  • 4,302
  • 10
  • 50
  • 104

2 Answers2

3

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).

Denis Mysenko
  • 6,366
  • 1
  • 24
  • 33
0

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/
kosta
  • 4,302
  • 10
  • 50
  • 104