IpToCidr関数
function ip2cidr($ip_start,$ip_end) {<br /> if(long2ip(ip2long($ip_start))!=$ip_start or long2ip(ip2long($ip_end))!=$ip_end) return !trigger_error('ip 不合法', E_USER_NOTICE); <br /> $ipl_start = ip2long($ip_start);<br /> $ipl_end = ip2long($ip_end);<br /> if($ipl_start>0 && $ipl_end<0) $delta = ($ipl_end + 4294967296) - $ipl_start;<br /> else $delta = $ipl_end - $ipl_start;<br /> $netmask = sprintf('%032b', $delta);<br /> if(ip2long($ip_start)==0 && substr_count($netmask,"1")==32) return "0.0.0.0/0";<br /> if($delta<0 or ($delta>0 && $delta%2==0)) return !trigger_error("区间数量不合法 $delta", E_USER_NOTICE);<br /> for($mask=0; $mask<32; $mask++) if($netmask[$mask]==1) break;<br /> if(substr_count($netmask,"0")!=$mask) {<br /> $w = strrpos($netmask, '0') + 1;<br /> $m = pow(2, 32-$w) - 1;<br /> $ip_start = long2ip(($ipl_start & ~$m)+$m+1);<br /> return long2ip($ipl_start & ~$m) . "/$w," . ip2cidr($ip_start,$ip_end);<br /> };<br /> return "$ip_start/$mask";<br />}
$r = ip2cidr("36.96.0.1","36.223.255.255");<br />print_r($r);<br /><br />function ip2cidr($ip_start,$ip_end) {<br /> $res = array();<br /> if(long2ip(ip2long($ip_start))!=$ip_start or long2ip(ip2long($ip_end))!=$ip_end)<br /> return !trigger_error('ip 不合法', E_USER_NOTICE); <br /> $ipl_start = ip2long($ip_start);<br /> if($ipl_start < 0) $ipl_start += 0x100000000;<br /><br /> $ipl_end = ip2long($ip_end);<br /> if($ipl_end<0) $ipl_end += 0x100000000;<br /><br /> $ipl=$ipl_start;<br /> do {<br /> $k = strrpos(sprintf('%032b', $ipl), '1');<br /> $cidr = $k + 1;<br /> $dk = pow(2, 32-$k-1);<br /> $mask = $dk - 1;<br /> $res[] = sprintf("%s/%d", long2ip($ipl & ~$mask), $cidr);<br /> $ipl += $dk;<br /> }while($ipl < $ipl_end);<br /> return $res;<br />}
Array<br />(<br /> [0] => 36.96.0.1/32<br /> [1] => 36.96.0.2/31<br /> [2] => 36.96.0.4/30<br /> [3] => 36.96.0.8/29<br /> [4] => 36.96.0.16/28<br /> [5] => 36.96.0.32/27<br /> [6] => 36.96.0.64/26<br /> [7] => 36.96.0.128/25<br /> [8] => 36.96.1.0/24<br /> [9] => 36.96.2.0/23<br /> [10] => 36.96.4.0/22<br /> [11] => 36.96.8.0/21<br /> [12] => 36.96.16.0/20<br /> [13] => 36.96.32.0/19<br /> [14] => 36.96.64.0/18<br /> [15] => 36.96.128.0/17<br /> [16] => 36.97.0.0/16<br /> [17] => 36.98.0.0/15<br /> [18] => 36.100.0.0/14<br /> [19] => 36.104.0.0/13<br /> [20] => 36.112.0.0/12<br /> [21] => 36.128.0.0/9<br />)<br /><br />
$r = ip2cidr("36.96.0.0","36.223.255.255");<br />print_r($r);
Array<br />(<br /> [0] => 36.96.0.0/11<br /> [1] => 36.128.0.0/9<br />)<br /><br />
$r = ip2cidr("36.96.0.0","36.223.255.255");<br>print_r($r);<br><br>function ip2cidr($ip_start,$ip_end) {<br> $res = array();<br> if(long2ip(ip2long($ip_start))!=$ip_start または long2ip(ip2long($ip_end))!=$ip_end)<br> return !trigger_error('ip は不正です ', E_USER_NOTICE) ; <br> $ipl_start = ip2long($ip_start);<br> if($ipl_start <br> $ipl_end = ip2long($ip_end);<div class="clear"></div>