Belgarion has asked for the wisdom of the Perl Monks concerning the following question:
A routine to generate an array of octets given an IPv6 netmask. For example, netmask /3 generates an array of one containing e0, while a netmask of /9 generates an array of two containing ff 80.
The following code takes a numeric netmask value between 0 and 128 (including both) and returns an array of octets representing that netmask.
# # Return an array of bytes that correspond to an IPv6 netmask. # The MSB is returned as the first byte. # sub make_netmask { my $mask = shift; return if $mask < 0 or $mask > 128; my @bytes; while ($mask > 0) { my $off = ($mask >= 8) ? 0 : (8 - $mask); push @bytes, (0xff << $off) & 0xff; $mask -= 8; } return @bytes; } sub output { my $mask = shift; my @bytes = make_netmask($mask); print "$mask = ", join(' ', map { sprintf "%02x", $_ } @bytes), "\ +n"; } # Test some inputs output(0); output(3); output(8); output(9); output(127); output(128); __OUTPUT__ 0 = 3 = e0 8 = ff 9 = ff 80 127 = ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff fe 128 = ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
The above code works (as can be seen by the OUTPUT section); however, I have a feeling that the make_netmask function could be improved. It just feels a little too subtle to me. I know what it's doing now (and if I comment it more, I'll know six months from now), but I'm wondering if there is a more elegant (or cleaner) way to generate this list of octets. I would appreciate both Perl specific and algorithm centric ideas.
Thank you.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Generating IPv6 Masks
by Fletch (Bishop) on Apr 28, 2004 at 17:30 UTC | |
|
Re: Generating IPv6 Masks
by hv (Prior) on Apr 28, 2004 at 17:43 UTC | |
|
Re: Generating IPv6 Masks
by kvale (Monsignor) on Apr 28, 2004 at 18:00 UTC | |
|
Re: Generating IPv6 Masks
by Roy Johnson (Monsignor) on Apr 28, 2004 at 19:18 UTC |