On 07/14/2015 09:04 AM, Matthew Harris wrote:
Nice to see that people are still learning Perl! I'll see some code!

Hi Matthew,
Seems to me like you can do anything in Perl.  It is sweet.
Here is the code.

I use this for system administration (a lot of us here),
specifically yo set up my firewall.

You will love the equation to go from Short Mask to
Hex Mask.  A guy on the Perl group helped me with
it and I have no idea how he figured it out.

     $HexMask = ~((1 << (32 - $ShortMask)) - 1);

Wow.  Took me forever to understand what he did!

-T

GetNetwork.pl
<code>
#!/usr/bin/perl

# Given the ip and the short mask in the form of
# www.xxx.yyy.zz and xx, e.g. 192.168.244.134 26
# calculate the network

use strict;
use warnings; # You'll get little help here without these
my (  $ScriptName, $ip, $ShortMask, $HexIP, $HexMask,
     $NetworkDots, $num_args, $Network );

( $ScriptName = $0 ) =~ s{.*/}{};

# quit unless we have the correct number of command-line args
$num_args = $#ARGV + 1;
if ($num_args != 2) {
    print "You forgot something\n";
    print "Usage: $ScriptName  IP  ShortMask\n\n";
    exit 1;
}


$ip=$ARGV[0];
$ShortMask=$ARGV[1];


if ($ip =~ m/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/ ) {
   # print "$1 $2 $3 $4\n";
   if ($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255 ) {
      print "Invalid ip <$ip>\n";
      exit 1;
   }
   $HexIP = ($1 << 24) + ($2 << 16) + ($3 << 8) + $4;
}


$HexMask = ~((1 << (32 - $ShortMask)) - 1);
$Network = $HexIP & $HexMask;   # & is a bit wise AND

$NetworkDots= ($Network >> 24)
              . "." .
              (($Network >> 16 ) & 0xFF)
              . "." .
              (($Network >> 8 ) & 0xFF )
              . "." .
              ($Network & 0xFF );

# print "Your network for ip=$ip and Netmask=$ShortMask is $NetworkDots\n";
print "$NetworkDots\n";
</code>

Reply via email to