Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Manipulating IPs and masks

by claree0 (Hermit)
on Sep 03, 2001 at 18:00 UTC ( #109869=perlquestion: print w/replies, xml ) Need Help??

claree0 has asked for the wisdom of the Perl Monks concerning the following question:

As a part of a project, I need to manipulate an IP address and network mask, both in dotted notation, to give a network address in slash notation (i.e. becomes

I've written the sub shown below, but I don't know if my method for finding the number of bits in the netmask is the best way to do it.......

sub nets { # takes 2 args - IP address and network mask my $ip = $_[0]; my $mask = $_[1]; my $nets = inet_ntoa ((inet_aton($ip)) & (inet_aton($mask))); my $binmask = unpack ("B32", pack ("C4", split(/\./, $mask))); $binmask =~ /(10)/; my $bits = $-[1]+1; my $network = "$nets\/$bits"; return $network; }

Replies are listed 'Best First'.
Re: Manipulating IPs and masks
by rob_au (Abbot) on Sep 03, 2001 at 18:27 UTC
    There are two modules which I think you should have a look at - Net::CIDR and more importantly, Net::Netmask. The latter of these modules incorporates a number of functions for exactly what you are requiring. eg.
    use Net::Netmask; my ($block) = new Net::Netmask ("", ""); print $block->base(), "/", $block->bits(), "\n";


    Ooohhh, Rob no beer function well without!

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://109869]
Approved by root
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (1)
As of 2022-10-01 02:23 GMT
Find Nodes?
    Voting Booth?
    I prefer my indexes to start at:

    Results (126 votes). Check out past polls.