[Za-pm] FYI: IP to Integer and back
Nico Coetzee
nico at itfirms.co.za
Mon Jun 30 12:32:56 CDT 2003
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.
Let me know what you people think...
Cheers
--
Nico Coetzee
http://www.itfirms.co.za/
http://za.pm.org/
http://forums.databasejournal.com/
To the systems programmer, users and applications serve only to provide a
test load.
More information about the Za-pm
mailing list