Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Cidr {
- /** ***********************************/
- /** Usable part ***********************/
- /*** **********************************/
- public function isIpValid($ip){
- return filter_var($ip, FILTER_VALIDATE_IP);
- }
- public function isInOprRange($opr_range, $ip){
- if ( strpos($opr_range,';') !== false ) {
- $ips = explode(';', $opr_range);
- foreach ( $ips as $ip_range ) {
- if ( strpos($ip_range,'-') !== false ) {
- list($inicial, $final) = explode('-', $ip_range);
- if ( $this->simpleInRange($ip, $inicial, $final) ) {
- return true;
- }
- } else {
- if ( $ip == $ip_range ) {
- return true;
- }
- }
- }
- }
- return $opr_range == $ip;
- }
- public function simpleInRange($ip, $initial, $final){
- $initial = ip2long($initial);
- $final = ip2long($final);
- $ip = ip2long($ip);
- return ($ip >= $initial && $ip <= $final);
- }
- /** ***********************************/
- /** End of usable part ****************/
- /*** **********************************/
- public function getCidrByFirstLastIP($first, $last){
- $first = ip2long($first);
- $last = ip2long($last);
- $qtd = (($last - $first)+2);
- $q = 0;
- while($qtd/2 > 1) {
- $q++;
- $qtd = $qtd/2;
- }
- return 32-($q+1);
- }
- public function getTotalIPsFromCidr($cidr) {
- return 1 << (32 - $cidr);
- }
- public function getFirstUsableIP($ip, $cidr){
- return long2ip(ip2long($this->getNetworkAddress($ip, $cidr)) + 1);
- }
- public function getLastUsableIP($ip, $cidr) {
- return long2ip(ip2long($this->getFirstUsableIP($ip, $cidr)) + (1 << (32 - $cidr)) -2);
- }
- public function isIPInRange($range, $cidr, $ip){
- // Calculando o range
- $initial = ip2long($this->getFirstUsableIP($range, $cidr));
- $final = ip2long($this->getLastUsableIP($range, $cidr));
- $ip = ip2long($ip);
- return ($ip >= $initial && $ip <= $final);
- }
- public function getNetmaskByCidr($cidr){
- $bin = '';
- for ( $i=1; $i<=32; $i++ ) {
- $bin .= ($cidr >= $i) ? '1' : '0';
- }
- $netmask = long2ip(bindec($bin));
- if ($netmask == '0.0.0.0') return false;
- return $netmask;
- }
- public function getCidrByNetmask($netmask){
- $bits = 0;
- $netmask = explode('.', $netmask);
- foreach ($netmask as $oct) {
- $bits += strlen(str_replace('0', '', decbin($oct)));
- }
- return $bits;
- }
- public function getNetworkAddress($ip, $cidr){
- return long2ip((ip2long($ip)) & ((-1 << (32 - (int)$cidr))));
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement