0

How can I get all IPv4 and IPv6 external addresses of the server the script is running on?

I have managed to put together a code that uses CLI ifconfig and some regular expressions to get them but I thought there could be a better way.

NikiC
  • 100,734
  • 37
  • 191
  • 225
transilvlad
  • 13,974
  • 13
  • 45
  • 80
  • 1
    Related to [Get local network interface addresses using only proc](http://stackoverflow.com/questions/5281341/get-local-network-interface-addresses-using-only-proc) – Drux Apr 09 '14 at 10:29
  • In common case - you'll have to deal with `system` + `ipconfig`-like solutions. But if you want to get, for example, DNS-saaociated records you may want to use [`dns_get_record()`](http://php.net/dns_get_record) like `dns_get_record('google.com')`. You'll have to deal with your hostname, of curse, - and it's not same as just get all public addresses for your server (you'll get DNS records) – Alma Do Apr 09 '14 at 10:31
  • As @Drux pointed - but the second [answer](http://stackoverflow.com/a/14725655/840409). One way is to use that bash script, call it with `exec()` :( and parse the output. You can change the output of the bash script. You can also try to convert that script to php. – Borislav Sabev Apr 11 '14 at 12:44

1 Answers1

0
function get_public_ips($eth = 'eth0') {
  $ipv4 = array_filter(explode(';', preg_replace('/\s/', ';', shell_exec("ip -o -4 addr list " . $eth . " | awk '{print $4}' | cut -d/ -f1"))), 'trim');
  $ipv6 = array_filter(explode(';', preg_replace(Array('/([a-z0-9:]+).*/', '/\s/'), Array('$1', ';'), shell_exec("ifconfig " . $eth . " | grep -Ev ':Link' | awk '/inet6/{print $3}'"))), 'trim');
  sort($ipv4);
  sort($ipv6);
  return Array('ipv4' => $ipv4, 'ipv6' => $ipv6);
}
transilvlad
  • 13,974
  • 13
  • 45
  • 80