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