41

Aside from the obvious (localhost, 127.0.0.1) does PHP (command line interface!) have a mechanism for discovering the IP of the computer the script is running on?

$_SERVER[*] will not work as this is not a Web app - this is a command line script.

TIA

Matthew Scharley
  • 127,823
  • 52
  • 194
  • 222
ChronoFish
  • 3,589
  • 5
  • 27
  • 38

7 Answers7

49

You can get the hostname by using gethostname

kabuko
  • 36,028
  • 10
  • 80
  • 93
  • 14
    Thanks - this was great: My solution was: getHostByName(getHostName()); – ChronoFish Nov 29 '09 at 04:35
  • 1
    There is a comment at the bottom of the page for <5.3. –  Nov 30 '09 at 04:08
  • 4
    word of caution: this method (and `gethostbynamel()`) will always return any IPs mapped in your server's local hosts file. In my testing (Ubuntu 11.10) this has meant that if the hostname you are checking against is mapped to 127.0.0.1 *anywhere* in /etc/hosts, it will override any other entries set. – pospi Mar 27 '12 at 07:28
42

try this it should return the ip address of the server

$host= gethostname();
$ip = gethostbyname($host);
Anish
  • 4,262
  • 6
  • 36
  • 58
  • 1
    @Besnik if you are using php version < 5.3.0 but >= 4.2.0 use this: $hostname = php_uname('n');. Above will work for php version > 5.3.0 – Anish Sep 20 '13 at 12:47
  • 1
    @aneesh +1 perfect! `php -r "echo gethostbyname(php_uname('n'));"` shows `192.168.178.20` ... and i'm using php 5.3.8 – Besnik Sep 21 '13 at 18:30
15

If you are working with PHP < 5.3, this may help (on *NIX based systems atleast):

 mscharley@S04:~$ cat test.php
#!/usr/bin/env php
<?php

function getIPs($withV6 = true) {
    preg_match_all('/inet'.($withV6 ? '6?' : '').' addr: ?([^ ]+)/', `ifconfig`, $ips);
    return $ips[1];
}

$ips = getIPs();
var_dump($ips);

 mscharley@S04:~$ ./test.php
array(5) {
  [0]=>
  string(13) "72.67.113.141"
  [1]=>
  string(27) "fe80::21c:c0ff:fe4a:d09d/64"
  [2]=>
  string(13) "72.67.113.140"
  [3]=>
  string(9) "127.0.0.1"
  [4]=>
  string(7) "::1/128"
}
 mscharley@S04:~$

Or, if you don't anticipate doing it often, then perhaps this would work (just don't abuse it):

$ip = file_get_contents('http://whatismyip.org/');
Matthew Scharley
  • 127,823
  • 52
  • 194
  • 222
  • Thanks - I like your Linux/Unix solution but for this app I'm running on Windows... (Yes I know... PHP CLI on Windows?!). The webservice is nice to know about - I'll have to keep it in mind for when I need "outside the firewall IP" :). – ChronoFish Nov 29 '09 at 04:44
  • whatismyip.org is dead now. Better https://whatismyhostname.com/raw/hostname/ this one for example – djdance May 14 '21 at 07:45
8

I know this is a fairly old question, but there doesn't seem to be a definitive answer (in as much as one is possible.) I've had a need to determine this value, both on *NIX boxes and on Win X boxes. Also from a CLI executed script as well as a non-CLI script. The following function is the best I've come up with, which borrows on different concepts people have spoke of over the years. Maybe it can be of some use:

function getServerAddress() {
    if(isset($_SERVER["SERVER_ADDR"]))
    return $_SERVER["SERVER_ADDR"];
    else {
    // Running CLI
    if(stristr(PHP_OS, 'WIN')) {
        //  Rather hacky way to handle windows servers
        exec('ipconfig /all', $catch);
        foreach($catch as $line) {
        if(eregi('IP Address', $line)) {
            // Have seen exec return "multi-line" content, so another hack.
            if(count($lineCount = split(':', $line)) == 1) {
            list($t, $ip) = split(':', $line);
            $ip = trim($ip);
            } else {
            $parts = explode('IP Address', $line);
            $parts = explode('Subnet Mask', $parts[1]);
            $parts = explode(': ', $parts[0]);
            $ip = trim($parts[1]);
            }
            if(ip2long($ip > 0)) {
            echo 'IP is '.$ip."\n";
            return $ip;
            } else
            ; // TODO: Handle this failure condition.
        }
        }
    } else {
        $ifconfig = shell_exec('/sbin/ifconfig eth0');
        preg_match('/addr:([\d\.]+)/', $ifconfig, $match);
        return $match[1];
    }
    }
}
3

If all else fails, you could always exec ipconfig or ifconfig, depending on your platform, and parse the result.

antik
  • 5,282
  • 1
  • 34
  • 47
  • Had I not been running 5.3 I would have fallen back on an OS level solution like this. Thanks! – ChronoFish Nov 29 '09 at 04:39
  • not sure how reliable, but you could skip exec() and use php_uname('n') to pull the hostname to pass to pass to getHostByName() – joshtronic Mar 31 '11 at 01:45
0

If you want to find local ip v4 and not WSL address.

Thanks https://stackoverflow.com/users/272555/impressthenet-web-developer for the https://stackoverflow.com/a/6256719/15610724
I rewrote the code for Windows 10 and php 7.4:

function getServerAddrAndName() {
  $serverName = getHostName();
  $addr = 'unknown';

  if (stristr(PHP_OS, 'WIN')) {
    // WIN 10 checked
    $lines = [];
    exec('ipconfig', $lines);
    // print_r($lines);
    $inWsl = FALSE;
    foreach($lines as $i => $line) {
      if ($line && stripos($line, '  ') !== 0) {
        // header-information
        $inWsl = stripos($line, '(WSL)');
        continue;
      }
      if (!$line || $inWsl) {
        // information is null or from WSL connect
        continue;
      }
      if ((stripos($line,'IP Address') || stripos($line, 'IPv4 Address')) && stripos($line,':')) {
        [, $ip] = explode(':', $line);
        $matches = [];
        $reg = '/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/';
        if (preg_match($reg, $ip, $matches)) {
          [$ip] = $matches;
          if (filter_var($ip, FILTER_VALIDATE_IP)) {
            $addr = $ip;
            break;
          }
        }
      }
    }
  } else {
    // Ubuntu 20.04 checked
    $addr = shell_exec("ip addr show eth0 | grep \"inet\b\" | awk '{print $2}' | cut -d/ -f1");
  }

  return ['serverAddr' => $addr, 'serverName' => $serverName];
}
-2

$ip = file_get_contents('http://icanhazip.com/');

echo $ip;