PHP how to get local IP of system

PhpIp Address

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

From CLI

PHP < 5.3.0
$localIP = getHostByName(php_uname('n'));

PHP >= 5.3.0
$localIP = getHostByName(getHostName());

Solution 2 - Php

$_SERVER['SERVER_ADDR']

Solution 3 - Php

This is an old post, but get it with this:

function getLocalIp()
{ return gethostbyname(trim(`hostname`)); }

For example:

die( getLocalIp() );

Found it on another site, do not remove the trim command because otherwise you will get the computers name.

BACKTICKS (The special quotes): It works because PHP will attempt to run whatever it's between those "special quotes" (backticks) as a shell command and returns the resulting output.

gethostbyname(trim(`hostname`));

Is very similar (but much more efficient) than doing:

$exec = exec("hostname"); //the "hostname" is a valid command in both windows and linux
$hostname = trim($exec); //remove any spaces before and after
$ip = gethostbyname($hostname); //resolves the hostname using local hosts resolver or DNS

Solution 4 - Php

A reliable way to get the external IP address of the local machine would be to query the routing table, although we have no direct way to do it in PHP.

However we can get the system to do it for us by binding a UDP socket to a public address, and getting its address:

$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_connect($sock, "8.8.8.8", 53);
socket_getsockname($sock, $name); // $name passed by reference

// This is the local machine's external IP address
$localAddr = $name;

socket_connect will not cause any network traffic because it's an UDP socket.

Solution 5 - Php

try this (if your server is Linux):

$command="/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
$localIP = exec ($command);
echo $localIP;

Solution 6 - Php

Depends what you mean by local:

If by local you mean the address of the server/system executing the PHP code, then there are still two avenues to discuss. If PHP is being run through a web server, then you can get the server address by reading $_SERVER['SERVER_ADDR']. If PHP is being run through a command line interface, then you would likely have to shell-execute ipconfig (Windows) / ifconfig (*nix) and grep out the address.

If by local you mean the remote address of the website visitor, but not their external IP address (since you specifically said 192.*), then you are out of luck. The whole point of NAT routing is to hide that address. You cannot identify the local addresses of individual computers behind an IP address, but there are some tricks (user agent, possibly mac address) that can help differentiate if there are multiple computers accessing from the same IP.

Solution 7 - Php

hostname(1) can tell the IP address: hostname --ip-address, or as man says, it's better to use hostname --all-ip-addresses

Solution 8 - Php

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;

?>

Solution 9 - Php

You may try this as regular user in CLI on Linux host:

function get_local_ipv4() {
  $out = split(PHP_EOL,shell_exec("/sbin/ifconfig"));
  $local_addrs = array();
  $ifname = 'unknown';
  foreach($out as $str) {
    $matches = array();
    if(preg_match('/^([a-z0-9]+)(:\d{1,2})?(\s)+Link/',$str,$matches)) {
      $ifname = $matches[1];
      if(strlen($matches[2])>0) {
        $ifname .= $matches[2];
      }
    } elseif(preg_match('/inet addr:((?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3})\s/',$str,$matches)) {
      $local_addrs[$ifname] = $matches[1];
    }
  }
  return $local_addrs;
}

$addrs = get_local_ipv4();
var_export($addrs);

Output:

array (
  'eth0' => '192.168.1.1',
  'eth0:0' => '192.168.2.1',
  'lo' => '127.0.0.1',
  'vboxnet0' => '192.168.56.1',
)

Solution 10 - Php

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}'")

Solution 11 - Php

$localIP = gethostbyname(trim(exec("hostname")));

I tried in Windows pc and Its worked and also think that Will work on Linux to.

Solution 12 - Php

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.

Solution 13 - Php

$_SERVER['SERVER_NAME']

It worked for me.

Solution 14 - Php

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

Solution 15 - Php

I fiddled with this question for a server-side php (running from Linux terminal)

I exploded 'ifconfig' and trimmed it down to the IP address.

Here it is:

$interface_to_detect = 'wlan0';
echo explode(' ',explode(':',explode('inet addr',explode($interface_to_detect,trim(`ifconfig`))[1])[1])[1])[0];

And of course change 'wlan0' to your desired network device.

My output is:

192.168.1.5

Solution 16 - Php

In windows

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

Solution 17 - Php

If you are in a dev environment on OS X, connected via Wifi:

echo exec("/sbin/ifconfig en1 | grep 'inet ' | cut -d ' ' -f2");

Solution 18 - Php

$_SERVER['REMOTE_ADDR']
  • PHP_SELF Returns the filename of the current script with the path relative to the root

  • SERVER_PROTOCOL Returns the name and revision of the page-requested protocol

  • REQUEST_METHOD Returns the request method used to access the page

  • DOCUMENT_ROOT Returns the root directory under which the current script is executing

Solution 19 - Php

Try this

$localIP = gethostbyname(trim('hostname'));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionairView Question on Stackoverflow
Solution 1 - Phpandras.timView Answer on Stackoverflow
Solution 2 - PhpSergey EreminView Answer on Stackoverflow
Solution 3 - PhpCodebeatView Answer on Stackoverflow
Solution 4 - PhpArnaud Le BlancView Answer on Stackoverflow
Solution 5 - PhpGeorge DeacView Answer on Stackoverflow
Solution 6 - PhpFoscoView Answer on Stackoverflow
Solution 7 - Phpern0View Answer on Stackoverflow
Solution 8 - PhpChinthaka DevindaView Answer on Stackoverflow
Solution 9 - Phpab1965View Answer on Stackoverflow
Solution 10 - PhpMohammad IlbeygiView Answer on Stackoverflow
Solution 11 - PhpPratik BodaView Answer on Stackoverflow
Solution 12 - PhpKowsigan AtsayamView Answer on Stackoverflow
Solution 13 - PhpFakhamatiaView Answer on Stackoverflow
Solution 14 - PhpP.O.W.View Answer on Stackoverflow
Solution 15 - PhpGonenView Answer on Stackoverflow
Solution 16 - PhpAllenBooTungView Answer on Stackoverflow
Solution 17 - PhpgpupoView Answer on Stackoverflow
Solution 18 - Phpuser2301590View Answer on Stackoverflow
Solution 19 - Phpmatija kancijanView Answer on Stackoverflow