How Can to convert CIDR to Netmask Addresses ??

Started by jalalahmadi, March 08, 2017, 01:09:05 PM

Previous topic - Next topic
March 08, 2017, 01:09:05 PM Last Edit: March 08, 2017, 01:41:42 PM by jalalahmadi
Hi
I want convert CIDR to Netmask Addresses just for show to user in UI .

<select name="subnet" class="selectpicker" data-style="btn-default" data-width="auto" data-size="10" dataid="subnet">

<?php     for ($i = 32; $i > 0; $i--):?>

   <option value="<?=$i;?>" <?=$i == $pconfig['subnet'] ? "selected=\"selected\"" : "";?>><?=$i;?></option>
<?php                                    endfor;?>

</select>





Please help me .

Thank you

You could use something along the lines of one of these functions:

The first one is the simplest, you can simply use it like ipv4cidr2subnet($i) to return the subnet mask
Code (php) Select
<?phpfunction ipv4cidr2subnet($cidr) {    static $max_ip;    if (!isset($max_ip))        $max_ip = ip2long('255.255.255.255');    if ($cidr < 0 || $cidr > 32)        return NULL;    $subnet_long = $max_ip << (32 - $cidr);    return long2ip($subnet_long);}


The second is a bit more complex but will reduce execution time if displaying the list more than once per page and can be used in a foreach loop like this:
$cidr_subnets = ipv4_cidr_subnets();
foreach ($cidr_subnets as $i => $subnet):
Code (php) Select
<?phpfunction ipv4_cidr_subnets() {    static $subnets = [];    if (empty($subnets)) {        $max_ip = ip2long('255.255.255.255');        for ($i = 0; $i <= 32; $i++)            $subnets[$i] = long2ip($max_ip << (32 - $i));    }    return $subnets;}

Thank you djGrrr  :D :D ;) ;)
This function works fine ipv4cidr2subnet  .


<?php          for ($i = 32; $i > 0; $i--):?>

<option value="<?=$i;?>" <?=$i == $pconfig['subnet'] ? "selected=\"selected\"" : "";?>> <?= ipv4cidr2subnet($i);?>  ( /<?= $i;?> )</option>
       
<?php  endfor;?>