perl and network addresses

Ben Scott dragonhawk at gmail.com
Wed Mar 29 23:05:01 EST 2006


On 3/28/06, Paul Lussier <p.lussier at comcast.net> wrote:
> It's confusing.

  Sure is!  Wow, that's one wacky setup.  :)

> The 10.0.32/19 is an interesting beast.  The systems which live on it
> have 2 NICs, the primary eth0, which *always* have a 10.0.32/19
> based address (currently restricted to 10.0.33/24 for some reason?!),
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  As far as that restriction goes, I've read of crufty old code which
assume everything follows the old classful model, with strict
boundaries  even for subnets.   It might be that.

  As for the rest... wow... funky.  I do hope all that multi-homing to
the same network is for test/simulation procedures.  :)

  Okay, in return for taking the time and effort to explain all that,
I took the time to figure out how to get Perl to convert IP addresses.
 Hopefully the following sample code will help you out:

!/usr/bin/perl -w
use Socket qw(inet_aton inet_ntoa);
# address and mask in ASCII decimal dotted-quad notation
$addr = '10.0.32.42';
$mask = '255.255.224.0'; # 19
print ("addr: $addr/$mask\n");
# convert to "string" (which is really the four bytes of a 32-bit int)
$addr = inet_aton($addr);
$mask = inet_aton($mask);
# convert to native integers
# the 'N' tells unpack the string is 32-bit int, network order)
$addr = unpack('N', $addr);
$mask = unpack('N', $mask);
# use binary math to mask out net and host parts
$net  = $addr & $mask;
$host = $addr & ~$mask; # ~$m = complement of mask (binary NOT)
# convert to "string" form
$net  = pack('N', $net);
$host = pack('N', $host);
# convert to ASCII dotted-quad notation
$host = inet_ntoa($host);
$net  = inet_ntoa($net);
# survey says...
print ("net : $net\n");
print ("host: $host\n");

  Is that even close to what you were thinking of?

-- Ben




More information about the gnhlug-discuss mailing list