Skip to content

Instantly share code, notes, and snippets.

@unclego
Created April 2, 2017 14:37
Show Gist options
  • Save unclego/ff1c9348ec90de3bfa5d699655b46bac to your computer and use it in GitHub Desktop.
Save unclego/ff1c9348ec90de3bfa5d699655b46bac to your computer and use it in GitHub Desktop.
Get array of avaiable ip's fitered by criteria (eg. exclude local interfaces)
/**
* Rested on centos 5, 6, 7
* Requires yum install net-tools on centos 7
*/
class GetAvailableIpAdresses {
/**
* @var $excludeIp array of IP's to exclude in IPV4 format eg. 127.0.0.1
*/
private static $excludeIp;
/**
* Filter array
* @param array $excludeIp array of IP's to exclude in IPV4 format eg. 127.0.0.1
* @return array filtered array of avaiable ip's
*/
public static function get( $excludeIp = array( '127.0.0.1', '10.0.0.0/8', '192.168.0.0/16') ) {
self::$excludeIp = $excludeIp;
return array_filter( self::get_avaiable_ip_addresses(), array(get_class(), 'ip_range_filter'));
}
/**
* Get array of all avaiable ip's
* @return array of avaiable ip's
*/
private static function get_avaiable_ip_addresses() {
$nl = '\n';
$cmd = <<<EOT
ifconfig | grep "inet " | awk 'begin{FS="$nl";RS="$nl$nl"}{gsub(/addr:/, "");split($0,a," ");print a[2];}'
EOT;
return explode( PHP_EOL, trim(shell_exec($cmd)) );
}
/**
* Filter array
* @param string $ip IP to check in IPV4 format eg. 127.0.0.1
* @return boolean true if the ip is in this range / false if not.
*/
private static function ip_range_filter( $ip ) {
foreach ( self::$excludeIp as $range) {
if ( self::ip_range_check($ip, $range)) {
return false;
}
}
return true;
}
/**
* Check if a given ip is in a network
* @param string $ip IP to check in IPV4 format eg. 127.0.0.1
* @param string $range IP/CIDR netmask eg. 127.0.0.0/24, also 127.0.0.1 is accepted and /32 assumed
* @return boolean true if the ip is in this range / false if not.
*/
private static function ip_range_check( $ip, $range ) {
if ( strpos( $range, '/' ) == false ) {
$range .= '/32';
}
// $range is in IP/CIDR format eg 127.0.0.1/24
list( $range, $netmask ) = explode( '/', $range, 2 );
$range_decimal = ip2long( $range );
$ip_decimal = ip2long( $ip );
$wildcard_decimal = pow( 2, ( 32 - $netmask ) ) - 1;
$netmask_decimal = ~ $wildcard_decimal;
return ( ( $ip_decimal & $netmask_decimal ) == ( $range_decimal & $netmask_decimal ) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment