以下代码是一段其他用户发布的代码。
我想知道获取在“net['firstip']”和“net['lastip']”之间的每个IP地址的最佳方法是什么?
我尝试了几种将十进制转换为二进制的方法,但没有成功。我的想法是用for循环增加二进制的“firstip”,直到它达到“lastip”,并将每个步骤转换为一个新数组中的十进制等价值。
感谢任何帮助。 我在两个特定的片段***旁边标注了我想要找到的IP地址。
function zerofill($val,$len,$reverse = false){
while(strlen($val)<$len)
if($reverse)
$val .= "0";
else
$val = "0".$val;
return $val;
}
function hextoip($hex){
for($i=0;$i<4;$i++)
@$ip .= base_convert(substr($hex,$i*2,2),16,10).".";
$ip = substr($ip,0,-1);
return $ip;
}
function iptohex($ip){
$iparr = explode(".",$ip);
foreach($iparr as $i => $group){
@$hex .= zerofill(base_convert($group,10,16),2);
}
return $hex;
}
function hextobin($hex){
$bin = zerofill(base_convert($hex,16,2),32);
return $bin;
}
function bintohex($bin) {
$hex = zerofill(base_convert($bin,2,16),8);
return $hex;
}
function getnet($ip, $netmask){
$iphex = iptohex($ip);
$netbin = hextobin($iphex);
$maskhex = iptohex($netmask);
$maskbin = hextobin($maskhex);
$hostbits = substr($maskbin,strpos($maskbin,"0"));
$netbits = substr($maskbin,0,strpos($maskbin,"0"));
$nethex = bintohex(zerofill(substr($netbin,0,strlen($netbits)),32,true));
$hosts = pow(2,strlen($hostbits));
$available_hosts = $hosts-3;
$net["ip"] = $ip;
$net["mask"] = $netmask;
$net["network"] = hextoip($nethex);
$net["netstr"] = $net["network"]."/".strlen($netbits);
$net["hosts"] = $available_hosts;
*** $net["firstip"] = hextoip(zerofill(base_convert(base_convert($nethex,16,10)+1,10,16),8));;
*** $net["lastip"] = hextoip(zerofill(base_convert(base_convert($nethex,16,10)+$available_hosts+1,10,16),8));
$net["broadcast"] = hextoip(zerofill(base_convert(base_convert($nethex,16,10)+$available_hosts+2,10,16),8));
return $net;
} `
if(empty($mask)) $mask = 32;
和if($mask == 32) $start = $end = $ipLong;
- Viacheslav aka Lordz