# # IP Calculator. # IP/Net mask/CIDR/etc computations. # # Copyleft 2004 Anatoli Klassen. http://www.26th.net # function get($arr, $field) { return array_key_exists($field, $arr) ? $arr[$field] : null; } function net2cidr($net) { for($n = 0; $net; $n++) { $net = ($net << 1) & 0xFFFFFFFF; } return $n; } function cidr2net($cidr) { $net = 1; for($n = 0; $n < 31-$cidr; $n++) { $net = $net << 1 | 1; } return ~$net; } function bin2string($bin, $split) { $res = ""; for($p=31; $p >= 0; $p--) { $res .= ($bin & (1 << $p)) ? "1" : "0"; if(32-$p == $split) $res .= " "; if($p > 0 && $p % 8 == 0) $res .= "."; } return $res; } $ip = get($_GET, 'ip'); $mask = get($_GET, 'mask'); $cidr = get($_GET, 'cidr'); if($mask) $cidr = net2cidr(ip2long($mask)); else if($cidr) $mask = long2ip(cidr2net($cidr)); if($mask) { $lIp = ip2long($ip ? $ip : ''); $lMask = ip2long($mask); $lNet = $lIp & $lMask; $lBroadcast = $lNet | (~$lMask); $lMin = $lNet + 1; $lMax = $lBroadcast - 1; $net = long2ip($lNet); $broadcast = long2ip($lBroadcast); $min = long2ip($lMin); $max = long2ip($lMax); $bIp = bin2string($lIp, $cidr); $bMask = bin2string($lMask, $cidr); $bNet = bin2string($lNet, $cidr); $bBroadcast = bin2string($lBroadcast, $cidr); $bMin = bin2string($lMin, $cidr); $bMax = bin2string($lMax, $cidr); } ?>
ip | = $ip ?> | = $bIp ?> |
mask | = $mask ?> | = $bMask ?> |
net | = $net ?>/= $cidr ?> | = $bNet ?> |
broadcast | = $broadcast ?> | = $bBroadcast ?> |
min host | = $min ?> | = $bMin ?> |
max host | = $max ?> | = $bMax ?> |