Page 1 of 1
Resolve localhost ip address
Posted: Fri Jun 13, 2008 8:55 pm
by dghundt
I need to run a php script on a linux box that will resolve and reutrn its own ip address - the ip address of the local host. I have seen a lot of posts were the result is just 127.0.0.0, but I need the linux box's ip address that is seen by the LAN (like 192.168.0.2).
Thank you.
David
Re: Resolve localhost ip address
Posted: Fri Jun 13, 2008 9:07 pm
by Christopher
That would be $_SERVER["SERVER_ADDR"]. You should get familiar with phpinfo().

Re: Resolve localhost ip address
Posted: Fri Jun 13, 2008 9:49 pm
by WebbieDave
Is the script being invoked via a web server or command line? If the former, you can try $_SERVER['SERVER_ADDR'] but it may not always be available or yield useful results. Also, some web servers place its ip in $_SERVER['SERVER_NAME'] instead. If via command line, you can regex it from ifconfig. Keep in mind that an interface can have multiple ip addresses.
Re: Resolve localhost ip address
Posted: Fri Jun 13, 2008 11:25 pm
by Ambush Commander
If your script is not being called via a webserver, it will have to query the OS to find out the IP address. It's not something PHP would intrinsically know.
Re: Resolve localhost ip address
Posted: Sat Jun 14, 2008 1:27 pm
by dghundt
Thank you for your replies.
The sript would not be called via a webserver, just php script on a linux box (which does run apache). I have seen that C# has the ability to call an API that can get the server address, but I need to do it in php with a short script.
Is there no method I can call in php to query what the OS sees as the ip address? I see a suggestion for ifconfig and then use regular express to capture the ip address.
Re: Resolve localhost ip address
Posted: Sun Jun 15, 2008 10:34 am
by dghundt
#!/bin/sh
IP_ADDR=`/sbin/ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2
echo "SET VARIABLE IP_ADD $IP_ADDR"
exit 0;
Re: Resolve localhost ip address
Posted: Sun Jun 15, 2008 2:49 pm
by VladSun
A little fix:
dghundt wrote:IP_ADDR=`/sbin/ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2
-->
Code: Select all
IP_ADDR=`/sbin/ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2| cut -d" " -f1
OR by using iproute:
Code: Select all
ip route show | grep src | awk '{print $9}'