Skip to content

Instantly share code, notes, and snippets.

@tdebatty
Last active May 12, 2022 08:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdebatty/85abd7dd0f34a7b08ffa to your computer and use it in GitHub Desktop.
Save tdebatty/85abd7dd0f34a7b08ffa to your computer and use it in GitHub Desktop.
PHP : Get IP from interface
// !! this gist was created in 2015, it doesn't work on most modern distributions !!
// e.g: get_ip("eth0");
function get_ip($interface) {
$interface = escapeshellarg($interface);
$pattern = "/inet addr:(\d+\.\d+\.\d+\.\d+)/";
$text = shell_exec("ifconfig $interface");
preg_match($pattern, $text, $matches);
return $matches[1];
}
@AlexNodex
Copy link

You've got a typo...

$text = shell_exec("ifconfig $internface"); <---- $interface not $internface!

@tdebatty
Copy link
Author

Fixed, thanks @AlexNodex !

@AlexNodex
Copy link

Newer systems won't work with your regex either

$pattern = "/inet (?:addr\:)?(\d+\.\d+\.\d+\.\d+)/";

this will allow an optional addr: part which newer flavours of Ubuntu (and probably others) leave out of the ifconfig command

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment