113

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.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
air
  • 6,136
  • 26
  • 93
  • 125

22 Answers22

129

From CLI

PHP < 5.3.0

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

PHP >= 5.3.0

$localIP = getHostByName(getHostName());

andras.tim
  • 1,964
  • 1
  • 13
  • 23
  • 3
    This is the solution that worked for me and that avoids calling shells, operating system commands and all sorts of stuff that can open security holes or raise odd issues later. – Dario Fumagalli Jul 17 '14 at 10:59
  • 2
    Best response usually comes with simplicity. Like that. – m3nda Nov 30 '14 at 12:15
  • 1
    @andras.tim I like simple answers , however when I ran your script it's not returning my machine's IP address, it's returning the IP address used in my virtual machine..what could be the problem though? – Scarl Jul 03 '15 at 22:19
  • just be aware, this approach relies on DNS correctly resolving whatever the system's hostname is set to. that will not always be the case. – Justin McAleer Jul 11 '16 at 14:16
  • 3
    In cloud hosting environment, this may not return expected result. Because every host has more than 2 IPs. – UnixAgain Oct 25 '16 at 08:04
  • 2
    This returns 127.0.0.1 for me, even though there are eth0 and wlan0 devices present, which have their own DHCP-assigned addresses. – Ryan Griggs Nov 08 '17 at 17:58
  • 1
    Same here. Returns 127.0.1.1. Not sure whom it worked for. – FractalSpace Jul 11 '18 at 20:48
  • @FractalSpace, your `/etc/hosts` file is not configured properly. You should check the DNS >> IP resolution with e.g.: `ping HOSTNAME` – andras.tim Jul 11 '18 at 21:28
  • @andras.tim yes, that was my issue. I am still sticking with `$_SERVER['SERVER_ADDR']` solution. (BTW you mean `ping $HOSTNAME`) – FractalSpace Jul 12 '18 at 12:51
65
$_SERVER['SERVER_ADDR']
Sergey Eremin
  • 10,994
  • 2
  • 38
  • 44
  • 14
    Clarification: a computer can have several IP addresses. This variable is HTTP-only and contains the IP address the virtual host is running at. Given how vague the question is, it's hard to say if this is the expected answer. – Álvaro González Aug 14 '13 at 07:27
  • 1
    I think this is correct, because you need always the asigned ip, the one is responding you. If not, you must use @andras.tim's asnwers, because tells you the main ip of system. – m3nda Nov 30 '14 at 12:17
  • This is exactly what I wanted, because my servers are behind a load balancer so `getHostName` doesn't return the sites domain name. – Yep_It's_Me May 02 '18 at 02:29
  • This doesn't work if you are running inside a docker container – Freedo Jul 30 '19 at 04:16
36

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
Codebeat
  • 6,501
  • 6
  • 57
  • 99
  • 8
    @paul: Because of the special quotes, when you using normal quotes it doesn't work for some reason and when you remove the trim command it even doesn't work. It sounds weird i know. It is not nice to downvote the answer for that. Read the answer. – Codebeat Feb 12 '13 at 00:59
  • 2
    Backticks (`) are called the execution operator in PHP. What your doing in the first code block is almost the same as the exec command. See [PHP: Execution Operators - Manual](http://php.net/manual/en/language.operators.execution.php) – Christiaan Nov 12 '13 at 14:03
  • 2
    Not really the best idea. It is possible and valid for `gethostbyname` to return a loopback IP (e.g. 127.0.0.1) for the host machine. – nobody May 12 '14 at 20:01
  • 2
    This help me a lot , I thought there would be simple PHP function like **$_SERVER['REMOTE_ADDR'];** which didn't work, but this solution worked for me !!! – Pini Cheyni Jun 19 '16 at 12:10
31

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.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
  • 3
    This answer is WAY better than the others. Any reliance on the $_SERVER array is dependent on this running under Apache. This idea also works on a cron job. I'm using it to only execute certain functions if a server is running on the staging or the production LAN. Perfect! – Per May 02 '16 at 16:45
  • This is an elegent answer. I adapted it in in a script managing docker containers to get the ip of my host on the docker network: `$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); socket_connect($sock, $this->getDockerMachineIp(), 53);` – FatherShawn May 29 '17 at 13:39
  • It is more portable I guess. Also, it is important to mention `sockets` module should be installed and enabled on PHP. – Fabio Montefuscolo Feb 16 '18 at 15:34
  • yes, thankyou very much @Arnaud Le Blanc, its very helpful for me, i got my IP address with this technique – Abid Ali Nov 21 '19 at 07:46
23

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;
andrewsi
  • 10,807
  • 132
  • 35
  • 51
George Deac
  • 247
  • 2
  • 2
  • 12
    Not absolutely right. There is no guarantee `eth0` is the appropriate interface. – nobody May 12 '14 at 19:57
  • Thanks, this worked perfectly for me. Being able to set the interface helped! – Rahim Khoja May 04 '16 at 23:47
  • In my case (local IP in WiFi local network) I had to specify `wlan0` instead of `eth0` and to replace `'inet addr:'` with `'inet adr:'`, possibly due to the locale used on my system (fr_FR). Other than that, this answer was the solution I was looking for. Thanks! – sylbru Feb 14 '17 at 11:03
  • Well actually `'inet adr:'` worked in my terminal (french locale), but in the PHP script `'inet addr:'` was the correct value (english locale, I guess). – sylbru Feb 14 '17 at 11:06
16

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.

Taz
  • 3,718
  • 2
  • 37
  • 59
Fosco
  • 38,138
  • 7
  • 87
  • 101
  • 1
    And last but not least, ipconfig/ifconfig will most likely return several IP addresses: because a computer does not normally have one single address. Great answer. – Álvaro González Aug 14 '13 at 07:29
  • yes the whole point of NAT is to hide the local IP now check out https://www.whatismyip.com/ they know your internal ip address, also open this website using your mobile they knows your mobiles local ip address too. EDIT: Im using JioFi Router, on mobile im using mobile data on Android 9 AOSP Based rom – Rishabh Gusain Apr 02 '19 at 20:32
12

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

ern0
  • 3,074
  • 25
  • 40
12

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;

?>
Chinthaka Devinda
  • 997
  • 5
  • 16
  • 36
  • Well this doesn't really work for me using Ubuntu and I have on my wlo1 a private ipv4 ip and that is what I need not the public. Yours is giving the public IP. And that surely is not what I know to be local IP address.The question is about local IP. – Dlaw Mar 16 '22 at 11:26
9

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}'")
Mohammad Ilbeygi
  • 191
  • 3
  • 11
7

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',
)
ab1965
  • 131
  • 2
  • 3
  • `array('bond0'=>'10.66.42.83','bond1'=>'hosting Ip address','lo'=>'127.0.0.1', )` I got this. I added this code in php file, – Straw Hat Feb 24 '14 at 06:12
  • Good answer, thanx. `split()` function has been DEPRECATED as of PHP 5.3.0. so suggest using `explode()` instead – Thanu Nov 25 '15 at 03:32
5
$localIP = gethostbyname(trim(exec("hostname")));

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

Yash Parekh
  • 1,513
  • 2
  • 20
  • 31
Pratik Boda
  • 394
  • 2
  • 6
4

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.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Kowsigan Atsayam
  • 446
  • 1
  • 9
  • 20
3
$_SERVER['SERVER_NAME']

It worked for me.

Fakhamatia
  • 1,202
  • 4
  • 13
  • 24
3

In windows

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

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

P.O.W.
  • 1,895
  • 1
  • 16
  • 14
1

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
Gonen
  • 391
  • 3
  • 4
1

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;
GeorgeP
  • 784
  • 10
  • 26
0

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

echo exec("/sbin/ifconfig en1 | grep 'inet ' | cut -d ' ' -f2");
gpupo
  • 942
  • 9
  • 16
0

Function to get all system ip(s) on PHP / Windows.

function GetIPs(){
    $sa = explode("\n",shell_exec('ipconfig'));
    $ipa = [];
    foreach($sa as $i){
        if (strpos($i,'IPv4 Address')!==false){
            $ipa[] = trim(explode(':', $i)[1]);
        }
    }
    return($ipa);
}
P.O.W.
  • 1,895
  • 1
  • 16
  • 14
0

Get Local IPv4 Address, tested with RHEL:

function getLocalIPv4(){
    return str_replace(array("\n", "\t", "\r"),'',shell_exec("nmcli | grep inet4 | awk '{print $2}' | cut -d/ -f1 2>&1"));
}

Even better, tested with RHEL:

function getLocalIPv4(){
    return str_replace(array("\n", "\t", "\r", ' '),'',shell_exec('hostname -I 2>&1'));
}

Two things to note:

  1. array("\n", "\t", "\r") you have to use quotes and not ticks, otherwise it won't remove the carriage return. Not sure why.... "\t" not needed really....
  2. This function is meant for one interface.
Jeff Luyet
  • 424
  • 3
  • 10
-4
$_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

Sirko
  • 72,589
  • 19
  • 149
  • 183
-6

Try this

$localIP = gethostbyname(trim('hostname'));
Padmanathan J
  • 4,614
  • 5
  • 37
  • 75
matija kancijan
  • 1,205
  • 10
  • 11