Showing entries with tag "IP".

Found 3 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 by_ip_address @ips;
sub by_ip_address {
    return ip2long($a) <=> ip2long($b);
}

Note: You will need my ip2long() function for this to work.

Leave A Reply

PHP: Determine if an IP address is part of a given subnet

Given an IP address I need to determine if it is part of a subnet for whitelist/blacklist purposes.

$allowed = ip_in_subnet('65.182.224.40','65.182.224.0/24');
// Borrowed from http://php.net/manual/en/function.ip2long.php#82397
function ip_in_subnet($ip, $cidr) {
    list ($net, $mask) = explode ('/', $cidr);
    return (ip2long ($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($net);
}

I also ported this function to Perl:

sub ip_in_subnet {
    my ($ip, $cidr)  = @_;
    my ($net, $mask) = split('/', $cidr);

    my $ret = (ip2long ($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($net);

    return int($ret);
}

Note: You will need the ip2long function.

Leave A Reply

Perlfunc: ip2long

sub ip2long {
    my $ip = shift;
    my @ip = split(/\./,$ip);

    #Make sure it's a valid ip
    if ($ip !~ /\d{1,3}\.\d{1,3}\.\d{1,3}/) { return 0; }

    if (scalar(@ip) != 4) { return 0; }

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

    $i[0] = ($long & 0xff000000) >> 24;
    $i[1] = ($long & 0x00ff0000) >> 16;
    $i[2] = ($long & 0x0000ff00) >> 8;
    $i[3] = ($long & 0x000000ff);

    $i = "$i[0].$i[1].$i[2].$i[3]";
    return $i;
}
Leave A Reply