Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Perl > Perl Misc > [networking] Convert subnet mask <=> mask length

Reply
Thread Tools

[networking] Convert subnet mask <=> mask length

 
 
187
Guest
Posts: n/a
 
      07-28-2004
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.


 
Reply With Quote
 
 
 
 
Jim Liebgott
Guest
Posts: n/a
 
      07-29-2004
On Wed, 28 Jul 2004 16:18:43 -0700, 187 <(E-Mail Removed)>
wrote:


$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";


> 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.
>
>




--
Using Opera's revolutionary e-mail client: http://www.opera.com/m2/
 
Reply With Quote
 
 
 
 
Bart Lateur
Guest
Posts: n/a
 
      07-29-2004
Warren Block wrote:

>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";
}

--
Bart.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Add a private subnet to existing real class C subnet bubbleserver@gmail.com Cisco 5 01-18-2007 04:59 PM
cannot ping from subnet A to subnet B for a specific host soup_or_power@yahoo.com Cisco 16 08-04-2006 02:30 PM
Subnet a subnet mask? Vass Computer Support 1 08-26-2005 01:02 PM
RE: Can anyone point me to some good subnet & subnet mask how tos..... Anonymous MCSA 0 04-02-2004 10:25 AM
Subnet / Subnet Mask ---> IP calculation kielhd Perl Misc 3 11-09-2003 08:34 PM



Advertisments