http://www.perlmonks.org?node_id=942278


in reply to finding netmask for "arbitrary" ip address

Here's what I ended up doing; it does require Socket.pm, but from what I've seen so far that looks pretty standard. It uses inet_aton to convert ip, net, and mask to structs, &s them to compare, then returns the mask when it finds a hit.

use Socket; sub findMask { my ($ip, $nets) = @_; my ($net, $mask) = (); foreach my $i (@$nets) { ($net, $mask) = split(m[/], $i); my $netBin = inet_aton($net); my $maskBin = inet_aton($mask); my $maskedNet = ($netBin & $maskBin); if (((inet_aton($ip)) & $maskBin) eq $maskedNet) { return "$mask"; } } ## no match return -1; }