/** * Function to check the passed address is within the passed subnet * * The parameter is a comma separated string of subnet definitions. * Subnet strings can be in one of three formats: * 1: xxx.xxx.xxx.xxx/xx * 2: xxx.xxx * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses < 256 * Code for type 1 modified from user posted comments by mediator at * {@link http://au.php.net/manual/en/function.ip2long.php} * * @param string $addr The address you are checking * @param string $subnetstr The string of subnet addresses * @return boolean */ function address_in_subnet($addr, $subnetstr) { $subnets = explode(',', $subnetstr); $found = false; $addr = trim($addr); foreach ($subnets as $subnet) { $subnet = trim($subnet); if (strpos($subnet, '/') !== false) { /// type 1 list($ip, $mask) = explode('/', $subnet); $mask = 0xffffffff << (32 - $mask); $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask)); } else if (strpos($subnet, '-') !== false) {/// type 3 if (substr($subnet,15,1) == '-') { //filters out malformed addresses $addrsubstr = substr($addr,12,3); $commonstring = substr($subnet,0,11); $startno = substr($subnet,12,3); $endno = substr($subnet,16,3); if(substr($addr,0,11) == $commonstring){ if(($startno <= $addrsubstr) && ($endno >= $addrsubstr)){ $found = true; } } } } else { /// type 2 $found = (strpos($addr, $subnet) === 0); } if ($found) { break; } } return $found; }