Friday, April 3, 2009

IP Address 2 IP number

This conversion is very usefull when we want to found out where the IP address is coming from.
$iprange_lowerbound > $ip_num < $iprange_upperbound

Here is ways to convert IP address to IP number

use Socket;
$ip = "10.1.1.1";
chomp($ip);
my $ip_num = ip2long($ip);

sub ip2long {
        return sprintf("%u",unpack("l*", pack("l*", unpack("N*", inet_aton(shift)))));
}

And here is another way to do it, a simpler version without using external library

$ip = "10.1.1.1";
my @ipp = split (/\./,$ip);
$ip_num = $ipp[0]*256*256*256+$ipp[1]*256*256+$ipp[2]*256+$ipp[3];

So how do you convert back IP number to IP address?

No comments: