PHP how to get local IP of system

Viewed 261851

I need to get local IP of computer like 192.*.... Is this possible with PHP?

I need IP address of system running the script, but I do not need the external IP, I need his local network card address.

20 Answers

From CLI

PHP < 5.3.0

$localIP = getHostByName(php_uname('n'));

PHP >= 5.3.0

$localIP = getHostByName(getHostName());

It is very simple and above answers are complicating things. Simply you can get both local and public ip addresses using this method.

   <?php 
$publicIP = file_get_contents("http://ipecho.net/plain");
echo $publicIP;

$localIp = gethostbyname(gethostname());
echo $localIp;

?>

You can use this php code :

$localIP = getHostByName(getHostName());
  
// Displaying the address 
echo $localIP;

If you want get ipv4 of your system, Try this :

shell_exec("ip route get 1.2.3.4 | awk '{print $7}'")

It is easy one. You can get the host name by this simple code.

$ip = getHostByName(getHostName());

Or you can also use $_SERVER['HTTP_HOST'] to get the hostname.

$_SERVER['SERVER_NAME']

It worked for me.

For Windows:

exec('arp -a',$sa);
$ipa = [];
foreach($sa as $s)
    if (strpos($s,'Interface:')===0)
        $ipa[] = explode(' ',$s)[1];

print_r($ipa);

The $ipa array returns all local IPs of the system

In windows

$exec = 'ipconfig | findstr /R /C:"IPv4.*"';
exec($exec, $output);
preg_match('/\d+\.\d+\.\d+\.\d+/', $output[0], $matches);
print_r($matches[0]);

To get the public IP of your server:

$publicIP = getHostByName($_SERVER['HTTP_HOST']);
echo $publicIP;

// or

$publicIP = getHostByName($_SERVER['SERVER_NAME']);
echo $publicIP;

If none of these global variables are available in your system or if you are in a LAN, you can query an external service to get your public IP:

$publicIP = file_get_contents('https://api.ipify.org/');
echo $publicIP;

// or

$publicIP = file_get_contents('http://checkip.amazonaws.com/');
echo $publicIP;
Related