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
All content licensed under the Creative Commons License