Subnet Calculator in 9 Lines of PHP
I’ve been spending a lot of time studying for my Microsoft 70-642 exam, an important part of which is subnetting.As an intellectual exercise I wrote a subnet calculator. Enjoy:
1 2 3 4 5 6 7 8 9 | function subnet($hosts) { $bits = decbin($hosts) + 2; // Add 2 for Network ID and Broadcast $hostBits = strlen($bits); // find how many bits it takes to represent it $cidr = 32 - $hostBits; // Find slash-notation $binaryMask = str_repeat('1', $cidr) . str_repeat('0', $hostBits); // Subnet in binary $subnet = implode('.', array_map('bindec', str_split($binaryMask, 8))); // Subnet in dotted-decimal return array('hosts' => $hosts, 'hostBits' => $hostBits, 'cidr' => '/' . $cidr, 'binaryMask' => $binaryMask, 'subnet' => $subnet); } |
function subnet($hosts)
{
$hostBits = strlen((decbin($hosts) + 2)); // find how many bits it takes to represent it
$cidr = 32 – $hostBits; // Find slash-notation
$binaryMask = str_repeat(‘1’, $cidr) . str_repeat(‘0’, $hostBits); // Subnet in binary
$subnet = implode(‘.’, array_map(‘bindec’, str_split($binaryMask, 8))); // Subnet in dotted-decimal
return array(‘hosts’ => $hosts, ‘hostBits’ => $hostBits, ‘cidr’ => ‘/’ . $cidr, ‘binaryMask’ => $binaryMask, ‘subnet’ => $subnet);
}
function subnet($hosts)
{
$hostBits = strlen((decbin($hosts) + 2)); // find how many bits it takes to represent it
$cidr = 32 – $hostBits; // Find slash-notation
$binaryMask = str_repeat(’1′, $cidr) . str_repeat(’0′, $hostBits); // Subnet in binary
return array(‘hosts’ => $hosts, ‘hostBits’ => $hostBits, ‘cidr’ => ‘/’ . $cidr, ‘binaryMask’ => $binaryMask, ‘subnet’ => implode(‘.’, array_map(‘bindec’, str_split($binaryMask, 8))));
}