OPNsense Forum

Archive => 17.1 Legacy Series => Topic started by: jalalahmadi on March 08, 2017, 01:09:05 pm

Title: How Can to convert CIDR to Netmask Addresses ??
Post by: jalalahmadi on March 08, 2017, 01:09:05 pm
Hi
I want convert CIDR to Netmask Addresses just for show to user in UI .

Code: [Select]
<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
Title: Re: How Can to convert CIDR to Netmask Addresses ??
Post by: djGrrr on March 08, 2017, 08:51:17 pm
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]
<?php
function ipv4cidr2subnet($cidr) {
    static 
$max_ip;
    if (!isset(
$max_ip))
        
$max_ip ip2long('255.255.255.255');

    if (
$cidr || $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]
<?php
function 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;
}
Title: Re: How Can to convert CIDR to Netmask Addresses ??
Post by: jalalahmadi on March 12, 2017, 02:19:12 pm
Thank you djGrrr  :D :D ;) ;)
This function works fine ipv4cidr2subnet  .

Code: [Select]
<?php
          
for ($i 32$i 0$i--):?>

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