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?

2
  • It depends on OS. What operating system are you running? Commented Mar 7, 2016 at 5:05
  • I am using Amazon linux and also Cent OS for local development. Commented Mar 7, 2016 at 5:39

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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/ 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.