This is a small code snippet I wrote along time ago for a bigger framework I’ve created. No extra modules are required.
It calculates the netmask of a network based on the network address and network bit (CIDR notation).
#!/usr/bin/perl use strict; use warnings; sub _calc_netmask { my($subnet) = @_; # e.g.: 10.0.0.0/24 192.168.1.0/16 my($network, $netbit) = split /\//, $subnet; my $_bit = ( 2 ** (32 - $netbit) ) - 1; my ($full_mask) = unpack( "N", pack( "C4", 255,255,255,255 ) ); my $netmask = join( '.', unpack( "C4", pack( "N", ( $full_mask ^ $_bit ) ) ) ); return $netmask; } foreach my $line (){ chomp($line); printf "SUBNET: %18s | NETMASK: %15sn", $line, _calc_netmask($line); } __DATA__ 10.0.0.0/24 192.168.1.0/27 195.94.76.0/29 172.16.0.0/17 172.19.0.0/16 1.0.0.0/8 2.0.0.0/12 4.0.0.0/13
It produces the following output:
$ perl netmask_calc.pl SUBNET: 10.0.0.0/24 | NETMASK: 255.255.255.0 SUBNET: 192.168.1.0/27 | NETMASK: 255.255.255.224 SUBNET: 195.94.76.0/29 | NETMASK: 255.255.255.248 SUBNET: 172.16.0.0/17 | NETMASK: 255.255.128.0 SUBNET: 172.19.0.0/16 | NETMASK: 255.255.0.0 SUBNET: 1.0.0.0/8 | NETMASK: 255.0.0.0 SUBNET: 2.0.0.0/12 | NETMASK: 255.240.0.0 SUBNET: 4.0.0.0/13 | NETMASK: 255.248.0.0