OPNsense
  • Home
  • Help
  • Search
  • Login
  • Register

  • OPNsense Forum »
  • Archive »
  • 17.1 Legacy Series »
  • How Can to convert CIDR to Netmask Addresses ??
« previous next »
  • Print
Pages: [1]

Author Topic: How Can to convert CIDR to Netmask Addresses ??  (Read 3562 times)

jalalahmadi

  • Newbie
  • *
  • Posts: 15
  • Karma: 2
    • View Profile
How Can to convert CIDR to Netmask Addresses ??
« 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
« Last Edit: March 08, 2017, 01:41:42 pm by jalalahmadi »
Logged

djGrrr

  • Full Member
  • ***
  • Posts: 112
  • Karma: 22
    • View Profile
Re: How Can to convert CIDR to Netmask Addresses ??
« Reply #1 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 < 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]
<?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;
}
Logged

jalalahmadi

  • Newbie
  • *
  • Posts: 15
  • Karma: 2
    • View Profile
Re: How Can to convert CIDR to Netmask Addresses ??
« Reply #2 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;?>

                                       
Logged

  • Print
Pages: [1]
« previous next »
  • OPNsense Forum »
  • Archive »
  • 17.1 Legacy Series »
  • How Can to convert CIDR to Netmask Addresses ??
 

OPNsense is an OSS project © Deciso B.V. 2015 - 2023 All rights reserved
  • SMF 2.0.19 | SMF © 2021, Simple Machines
    Privacy Policy
    | XHTML | RSS | WAP2