function ip_addr_in_network($ip, $networkDef) { if (preg_match("/[a-zA-Z]/", $networkDef) == 1) { $networkDef = getAddrByHost($networkDef, '3'); } $ipDec = ip_addr_dec($ip); if ($ipDec < 1) { return false; } $ipBin = ip_addr_decbin($ipDec); //echo "ip : $ipBin\n"; $nDef = explode('/', $networkDef, 2); if (count($nDef) < 2) { $nDef[1] = '32'; } // 255.255.255.255 $nIpDec = ip_addr_dec($nDef[0]); //if ($nIpDec < 1) return false; $nIpBin = ip_addr_decbin($nIpDec); //echo "netip : $nIpBin\n"; $nMaskDec = ip_addr_dec($nDef[1]); $nMaskBin = $nMaskDec > 1 ? ip_addr_decbin($nMaskDec) : str_repeat('1', (int) $nDef[1]) . str_repeat('0', 32 - (int) $nDef[1]); //echo "netmask: $nMaskBin\n"; for ($i = 0; $i < 32; ++$i) { if ($nMaskBin[$i] == '1' && $ipBin[$i] != $nIpBin[$i]) { return false; } } return true; }
function ip_addr_network_add_sub($network, $sub_ip) { # simple OR for 2 binary strings, eg. # 11000000101010000000000100000000 # 00000000000000000000000010000010 # => 11000000101010000000000110000010 $binary_net = ip_addr_decbin(ip_addr_dec($network)); $binary_sub = ip_addr_decbin(ip_addr_dec($sub_ip)); if (strLen($binary_net) != 32 || strLen($binary_sub) != 32) { return false; } $binary_ip = ''; for ($i = 0; $i < 32; ++$i) { $binary_ip .= $binary_net[$i] == '1' || $binary_sub[$i] == '1' ? '1' : '0'; } $ip = long2ip(binDec($binary_ip)); return $ip ? $ip : false; }