Skip to content

Instantly share code, notes, and snippets.

@tdebatty
Last active May 12, 2022 08:26
Show Gist options
  • Select an option

  • Save tdebatty/85abd7dd0f34a7b08ffa to your computer and use it in GitHub Desktop.

Select an option

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

You've got a typo...

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

@tdebatty
Copy link
Copy Markdown
Author

Fixed, thanks @AlexNodex !

@AlexNodex
Copy link
Copy Markdown

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