Showing entries with tag "ip2long".

Found 1 entries

Perl: Sort an array of IP addresses

I have a list of IP addresses that I want sorted in a human readable fashion. A simple sort() on a list of IPs will not work because the octets may be: one, two, or three digits long which confuses sort(). Here is a simple sorting function for a list of IP addresses:

my @ips    = qw(198.15.0.20 4.2.2.1 10.11.1.1 10.100.1.1 65.182.224.40);
my @sorted = sort { &ip_sort } @ips;
sub ip_sort {
    local *ip2long = sub {
        my @ip = split(/\./,$_[0]);

        #Perform the bit shifting to align each octet in the long correctly
        my $ret = ($ip[0] << 24) + ($ip[1] << 16) + ($ip[2] << 8) + $ip[3];
        return $ret;
    };

    return ip2long($a) <=> ip2long($b);
}

This uses a modified version of ip2long() as a nested subroutine. This could be done with a normal sub too, but I wanted it to be one function that's easy to copy and paste.

Leave A Reply