[networking] Convert subnet mask <=> mask length

1

187

For example, how can I go from 255.255.252.0 to /22 (as in, for example,
150.10.10.10/22) and vice versa.

I've bane up and down both www.google.com and groups.google.com, tried
searching by perl group, and even globally, and nothing, just online
calculators. Calculators are nice tools, but I really want to know *how*
it's done :)

Thanks.
 
J

Jim Liebgott

$subnet='255.255.252.0';
@octets=split(/\./,$subnet);
$bits=40;
do
{
$last_octet=pop(@octets);
$bits-=8;
}
while (!$last_octet && @octets);
if (@octets)
{
while (!($last_octet%2))
{
$bits--;
$last_octet>>=1;
}
}
print $bits,"\n";
 
B

Bart Lateur

Warren said:
use Socket;

print '/', unpack('%32b*', inet_aton($ARGV[0])), "\n";

That's just beautiful.

It does depend on the fact that you assume the input will match the
binary pattern /^1*0*$/, and you can't be sure...

My version makes sure it does. It also follows a more conventional
route.

#!/usr/local/bin/perl -wl
use Socket;

my $ip = '255.255.252.0';

if(unpack('B*', inet_aton($ip)) =~ /^(1*)0*$/) {
print "/" . length $1;
} else {
print "No match";
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top