Location: PHPKode > scripts > CIDR Table > cidr-table/cidr_table_class.php
<?php

class CIDR_entry{
	var $length;
	var $mask;
	var $networks;
	var $type;
	var $hosts;
	
	function CIDR_entry($length){
		if($length<1 || $length>32){
			echo "ERROR: CIDR subnet size /$length is invalid<br>\n";
			exit;
		}
		$this->length = $length;

		$ones	= $length;
		$zeros	= 32-$length;
		$this->mask = str_repeat("1",$ones).str_repeat("0",$zeros);
		//echo "$length<br>\n";
		$this->mask = base_convert($this->mask,2,10);
		//echo inet_ntoa($this->mask)."<br>\n";

		//--- Compute Type of Network and number of Networks
		if($length>0 && $length<9){
			$this->type = "A";
			$this->networks = pow(2,(8-($this->length)));
		}elseif($length>8 && $length<17){
			$this->type = "B";
			$this->networks = pow(2,(16-($this->length)));
		}elseif($length>16 && $length<25){
			$this->type = "C";
			$this->networks = pow(2,(24-($this->length)));
		}else{
			$this->type = "C";
			$this->networks = "1/".pow(2,(($this->length)-24));
		}

		//Compute the number of hosts
		$this->hosts = pow(2,$zeros);		
		($this->hosts != 1)?$this->hosts = ($this->hosts-2):true;
		//echo $this->length." ".$this->networks." ".$this->type." ". $this->hosts."<br>\n";
	
	}
}
class CIDR_Table{
	var $cidr = array();

	function CIDR_Table(){
		
		for($i=1; $i<33; $i++){
			$this->cidr[$i] = new CIDR_entry($i);	
		}
	}
	function inet_ntoa($n) {
		$t=array(0,0,0,0);
		$msk = 16777216.0;
		$n += 0.0;
		if ($n < 1)
		    return ;
		for ($i = 0; $i < 4; $i++) {
		    $k = (int) ($n / $msk);
		    $n -= $msk * $k;
		    $t[$i]= $k;
		    $msk /=256.0;
		};
		$a=join('.', $t);
		return($a);
	}
	function print_table(){
	?>
	<table border="1" cellpadding="3" cellspacing="0">
		<tr>
			<th>CIDR Length</th>
			<th>Mask</th>
			<th># Networks</th>
			<th># Host</th>
		</tr>
	<?php
		for($i=1; $i<33; $i++){
			?>
			<tr>
				<td align="center">/<?= $this->cidr[$i]->length ?></td>
				<td align="center"><?= $this->inet_ntoa($this->cidr[$i]->mask) ?></td>
				<td><?= ($this->cidr[$i]->networks." ".$this->cidr[$i]->type) ?></td>
				<td><?= $this->cidr[$i]->hosts ?></td>
			</tr>
			<?php
		}
	?>
	</table>
	<?php
	}

}


?>
Return current item: CIDR Table