On Thu, Oct 16, 2008 at 05:44, Sandy lone <[EMAIL PROTECTED]> wrote:
> I need to translate an IP addr with its mask from this form:
>
> 192.168.1.30/255.255.255.0
>
> to this one:
>
> 192.168.1.30/24
>
>
> which module/method is right to use? Thanks.

A quick search of CPAN* turned up NetAddr::IP which seems to do what
you want.  I would probably say something like

#!/usr/bin/perl

use strict;
use warnings;
use List::Util qw<sum>;

print netmask_to_cidr("192.168.1.30/255.255.255.0"), "\n";

sub netmask_to_cidr {
        my ($ip_and_netmask) = shift;
        #FIXME: do better checking of arguments
        die "bad argument: $ip_and_netmask"
                unless my ($ip, $netmask) = $ip_and_netmask =~ m{(.*)/(.*)};

        #FIXME: this may be wrong, but I think we just need to count the number
        #of bits that are on
        my $cidr = sum map {(sprintf "%b", $_) =~ tr/1//} split /\./, $netmask;

        return "$ip/$cidr";
}


* http://search.cpan.org
** http://search.cpan.org/dist/NetAddr-IP/IP.pm


-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to