1

I'm writing a script that needs to list all the external IPs for the server. It needs to work with multiple NICs. What's the best method to get said IP addresses in PHP?

If it's any help, I found this question, however it is directed at Python and not PHP; Python, How to get all external ip addresses with multiple NICs

Community
  • 1
  • 1
Jack B
  • 547
  • 4
  • 22
  • 1
    You'll very likely be best off running an external shell command to collect the information. – Pekka Aug 21 '13 at 19:40
  • That's ok, however.. What command? – Jack B Aug 21 '13 at 19:41
  • 1
    This has nothing to do with PHP, since PHP has no facilities for this sort of thing. Find an external tool (e.g. `ifconfig`) from PHP and parse the output. – Marc B Aug 21 '13 at 19:44
  • `ifconfig |grep inet` does the job for me (although you still have to parse the output). I wouldn't be surprised if there were ready-made shell scripts for this that do the parsing; just saying you can look outside of PHP for this – Pekka Aug 21 '13 at 19:45
  • which operating system are you asking about? – hakre Aug 21 '13 at 20:03
  • It has to work on all Linux distributions and would be great if it would on Windows. However I doubt the latter would be possible without complexity. – Jack B Aug 21 '13 at 20:07

3 Answers3

3

To get the (IPv4) IPs of all interfaces except Link-local:

<?php
$command = '/sbin/ifconfig | awk -v RS="\n\n" \'{ for (i=1; i<=NF; i++) if ($i == "inet" && $(i+1) ~ /^addr:/) address = substr($(i+1), 6); if (address != "127.0.0.1") printf "%s\t%s\n", $1, address }\' | awk \'{ print $2}\'';
$ips = shell_exec($command);
echo $ips;
?>

Tested on Debian Linux.

busch
  • 44
  • 6
2

If you're using a Linux based server, this should do it for you:

$command = "/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
$ips = exec($command);
echo $ips;
Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
  • Not really, because you are only listing eth0 - the question was about ALL interfaces. – Sven Aug 21 '13 at 19:54
0

I think this may be the best one for you

$command = "/sbin/ifconfig | grep inet | grep -v ':\|127.0.0.1' | awk '{print $2}'";
exec($command, $ips);
return $ips;

hope this helps

Louis
  • 3
  • 4