Sep. 16th, 2008

wildernesscat: (Default)

A PHP function for converting a CIDR-style netmask to dotted notation (e.g. 10.0.0.1/8 => 10.0.0.1/255.0.0.0).

private function convertNetmask($cidr_mask)
{
        if ($cidr_mask <= 0) return '0.0.0.0';

        $bit_mask = 0x80000000;
        for ($i = $cidr_mask - 1; $i > 0; --$i)
                $bit_mask >>=1;
        return long2ip($bit_mask);
}

The only simpler method I can think of, is creating a static look up table (like this one).

Update: A one-liner that does the same thing:

private function convertNetmask($cidr_mask)
{
        return long2ip(0xFFFFFFFF ^ (pow(2, 32 - $cidr_mask) - 1));
}

Originally posted on wildernesscat.vox.com

 

Profile

wildernesscat: (Default)
Danny Dorfman

March 2018

S M T W T F S
    123
4 5678910
11121314151617
18192021 222324
25262728293031

Style Credit

Page generated Dec. 20th, 2025 10:01 am
Powered by Dreamwidth Studios

Expand Cut Tags

No cut tags

Most Popular Tags