网络广播地址计算方法:
(1)IP地址与子网掩码进行“位与”运算,得到网络地址
(2)子网掩码“取反”运算,然后与网络地址进行“位或”运算,得到广播地址
01 //ip地址转换广播地址
02 private function ip2broadcast($ip,$mask){
03 $ipSplit = explode('.',$ip);
04 $maskSplit = explode('.',$mask);
05 $broadcast = null;
06 for ($i=0; $i < 4; $i++) {
07 $ipBin = sprintf("%b",$ipSplit[$i]);
08 while((8-strlen($ipBin))>0) $ipBin = "0".$ipBin;
09
10 $maskBin = sprintf("%b",$maskSplit[$i]);
11 while((8-strlen($maskBin))>0) $maskBin = "0".$maskBin;
12
13 $broadcastBin = null;
14 for ($j=0; $j < 8; $j++) {
15 $broadcastBin .= (!intval(substr($maskBin, $j , 1))) |
16 (intval(substr($ipBin, $j , 1)) &intval(substr($maskBin, $j , 1)));
17 }
18
19 if ($i>0) $broadcast .= ".";
20 $broadcast .= bindec($broadcastBin);
21 }
22 return $broadcast;
23 }
|