views:

972

answers:

3

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

+1  A: 

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

antik
Had I not been running 5.3 I would have fallen back on an OS level solution like this. Thanks!
ChronoFish
+1  A: 

You can use: http://au2.php.net/manual/en/function.gethostname.php

Thanks - this was great: My solution was: getHostByName(getHostName());
ChronoFish
It is a 5.3 solution - but thankfully I'm running 5.3
ChronoFish
There is a comment at the bottom of the page for <5.3.
+3  A: 

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
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