dirk

Here is the

Perl

  adaptation of the IP conversion.

It's a test script which includes the respective subroutines to
convert the IP address into an integer and vice versa.


#!/usr/bin/

perl

 

use strict;
use warnings;
use Carp;

my $ip = '255.255.255.255';

my $ip_int = ip_to_int($ip);

my $ip_new = int_to_ip($ip_int);

print "$ip -> $ip_int -> $ip_new ";

exit;

#-------------------------------------------------------------------------------

sub ip_to_int {
    my ($ip) = @_;

    my $ip_int;
    if ( my ( $ip_a, $ip_b, $ip_c, $ip_d ) =
        $ip =~ m{ ^(d{1,3}).(d{1,3}).(d{1,3}).(d{1,3})$ }xms )
    {
        $ip_int =
            ( $ip_a * 256**3 ) + ( $ip_b * 256**2 ) + ( $ip_c * 256 ) + $ip_d;
    }
    else {
        croak "Invalid IP Address: $ip";
    }

    return $ip_int;
}

#-------------------------------------------------------------------------------

sub int_to_ip {
    my ($ip_int) = @_;

    my $ip =
          ( ( $ip_int / 256**3 ) % 256 ) . q{.}
        . ( ( $ip_int / 256**3 ) % 256 ) . q{.}
        . ( ( $ip_int / 256**3 ) % 256 ) . q{.}
        . ( $ip_int % 256 );

    return $ip;
}

#-------------------------------------------------------------------------------

perkiset

Nice Dirk and easily readable. Here it is done in

PHP

  as well:

http://www.perkiset.org/forum/

php

 /converting_ip_adrresses_to_integers_and_back-t87.0.html

... perhaps we need to think about how to structure this so that when we have the same functionality described in multiple languages it is easily found and read in that way... gonna have to think about how to do that.

Thanks!

/p


Perkiset's Place Home   Politics @ Perkiset's