[Za-pm] FYI: IP to Integer and back

Nick Cleaton nick at cleaton.net
Wed Jul 2 05:57:05 CDT 2003


On Mon, Jun 30, 2003 at 07:32:56PM +0200, Nico Coetzee wrote:
> 
> I don't know if some of you work a lot with IP addresses, but it's easier to 
> manipulate large amounts of addresses if you work with the Integer value of 
> an IP. Here is a short script to illustrate the use:
> 
> <CODE>
> #!/usr/bin/perl
> 
> $ipnumber = ip2ipn( "192.168.0.1" );
> if ( $ipnumber ) {
> 	print "IPN : $ipnumber\n";
> 	$ip = ipn2ip( $ipnumber );
> 	if ( $ip ) {
> 		print "IP  : $ip\n";
> 	}
> }
> 
> sub ip2ipn {
> 	# this sub will change an IP to the Integer value
> 	if ( $_[0] =~ /^\d+\.\d+\.\d+\.\d+/ ) {
> 		$_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
> 		my $num = (16777216*$1)+(65536*$2)+(256*$3)+$4;
> 		return $num;
> 	} else {
> 		return 0;
> 	}
> }
> 
> sub ipn2ip {
> 	# this sub returns the IP address from an Integer
> 	# logical range is from 0.0.0.1 to 255.255.255.255
> 	if ( ( $_[0] > 0 ) && ( $_[0] < 4294967295 ) ) {
> 		my $ipn = $_[0];
> 		my $w=($ipn/16777216)%256;
> 		my $x=($ipn/65536)%256;
> 		my $y=($ipn/256)%256;
> 		my $z=$ipn%256;
> 		my $ipn = $w . "." . $x . "." . $y . "." . $z;
> 		return $ipn;
> 	} else {
> 		return 0;
> 	}
> }
> </CODE>
> 
> I assume there are other modules to handle this - but then, this is a learning 
> experience :) BTW - let's see how we can improve this - making the subs less 
> lines etc.

If I'm allowed to use Socket.pm then I can make the subs much shorter:

<CODE>
#!/usr/bin/perl

use Socket;

$ipnumber = ip2ipn( "192.168.0.1" );
if ( $ipnumber ) {
        print "IPN : $ipnumber\n";
        $ip = ipn2ip( $ipnumber );
        if ( $ip ) {
                print "IP  : $ip\n";
        }
}

sub ip2ipn {
     return unpack 'N', inet_aton(shift);
}

sub ipn2ip {
    return inet_ntoa( pack 'N', shift );
}

</CODE>

--
Nick



More information about the Za-pm mailing list