Created
September 9, 2011 11:12
-
-
Save kevinlebrun/2dfcd55e41fc64ad17fd to your computer and use it in GitHub Desktop.
PHP Network Helpers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function is_in_subnet($subnet, $ip) | |
{ | |
list($subnet_ip, $subnet_mask) = explode('/', $subnet); | |
$begin = (ip2long($subnet_ip) & ip2long($subnet_mask)) + 1; | |
$end = (ip2long($subnet_ip) | (~ip2long($subnet_mask))) + 1; | |
$ip = ip2long($ip); | |
return ($ip >= $begin && $ip <= $end); | |
} | |
function cidr2mask($cidr) | |
{ | |
return long2ip(-1 << (32 - (int) $cidr)); | |
} | |
function mask2cidr($mask) | |
{ | |
$long = ip2long($mask); | |
$base = ip2long('255.255.255.255'); | |
return 32 - log(($long ^ $base) + 1, 2); | |
} | |
function check_subnet($subnet) | |
{ | |
if (strpos($subnet, '/') === false) { | |
throw new \InvalidArgumentException('IP/CIDR format required for the subnetwork'); | |
} | |
list($ip, $cidr) = explode('/', $subnet); | |
$network = (-1 << (32 - (int) $cidr)) & ip2long($ip); | |
return $ip === $network; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment