Skip to content

Instantly share code, notes, and snippets.

@kevinlebrun
Created September 9, 2011 11:12
Show Gist options
  • Save kevinlebrun/2dfcd55e41fc64ad17fd to your computer and use it in GitHub Desktop.
Save kevinlebrun/2dfcd55e41fc64ad17fd to your computer and use it in GitHub Desktop.
PHP Network Helpers
<?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