Get IP address from ifconfig using PHP

Marcos picture Marcos · Nov 14, 2012 · Viewed 11.4k times · Source

I have the next php code:

<?php
   $ip = shell_exec("/sbin/ifconfig  | grep 'inet:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'");
   echo $ip;
?>

It works fine when I run it from the command line ($php5 ip.php), but when I run it from my browser it shows nothing (http://localhost/ip.php).

By the way, I'm trying to print my IP address but whenever I use $_SERVER['SERVER_ADDR']; I get 127.0.0.1.

Answer

ivankoni picture ivankoni · Nov 14, 2012

It will work without colon next to 'inet'

grep 'inet '