Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Manipulating IPs and masks

by claree0 (Hermit)
on Sep 03, 2001 at 18:00 UTC ( [id://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. 192.168.1.5 255.255.255.0 becomes 192.168.1.0/24)

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 ("192.168.1.5", "255.255.255.0"); print $block->base(), "/", $block->bits(), "\n";

     

     
    Ooohhh, Rob no beer function well without!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (7)
As of 2024-04-23 10:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found