perlsubnetcidrnetmask

Perl Calculate netmask from CIDR


I found a little function on a website here http://jmorano.moretrix.com/2010/08/calculate-netmask-in-perl I am using it, but it does not produce the same thing as he gets.

I am putting a CIDR address in a variable like this :

126.126.126.250/24

The function should return something like 255.255.255.0 But instead, it returns

0.0.0.255

The only thing that i modified in the function is

my($network, $netbit) = split ///, $subnet;

TO

my($network, $netbit) = split /\//, $subnet;

and the return is just changed into "print" return $netmask; TO print "$netmask \n" ;

I guess there's something wrong in here

    my $_bit         = ( 2 ** (32 - $netbit) ) - 1;

Because when i print $_bit i just have "255"

But i can't figure what is it.


Solution

  • One more backslash needed,

    my ($full_mask)  = unpack( "N", pack( "C4", split(/\./, '255.255.255.255') ) );
                                                       ^
    

    although it would make more sense as

    my ($full_mask)  = unpack( "N", pack( "C4", 255,255,255,255 ) );
    

    or

    my ($full_mask)  = unpack( "N", pack( "C4", (255) x4 ) );