Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: regex for classless IP subnets

by kal (Hermit)
on Mar 24, 2003 at 19:57 UTC ( [id://245516]=note: print w/replies, xml ) Need Help??


in reply to regex for classless IP subnets

If you want to avoid the overhead of a full module, you could probably to it with two functions. First, something to convert IP addresses into integers, like:

sub ip_2_int { my ($ip) = @_; $ip =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/ or die "$ip is an invalid address"; return ($1<<24)|($2<<16)|($3<<8)|$4; }

Then, you just want to compare the network parts of the IP address with the network address. So, obviously you need to create the netmask (i.e., /16 is (2**16)-1, I think?), and then just compare the numbers, i.e.:

if (($ipaddress|$netmask)==$network) { # then $ipaddress is in the range $network/$netmask defines }

You could obviously wrap that in a common function, perhaps something like:

sub isInNetwork { my ($cidr_str, $ipaddress_str) = @_; my ($network_str, $netmask_str) = split ('/', $cidr_str); my ($network, $ip) = (ip_2_int ($network_str), ip_2_int ($ipaddress_str)); return ($network==($ip|(2**$network-1)); } print "10.0.50.12 is in 10/8!\n" if isInNetwork ('10.0.0.0/8', '10.0.50.12');

Or something (much more error checking would of course be required ;). That's off the bat, unfortunately I don't have access to a Perl right now :/ But, I'm pretty sure it's not supposed to be sufficiently complex to require a regex - remember, C programmers use IP addresses (socket.h), so it's can't be very difficult.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-20 04:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found