Friday, May 6, 2011

calculate long ip from Ip address - IP number from IP address - ip2number

Today, i came across to compare IP addresses and needed to have it stored in the long int as well. its also called IP number

Reason for storing values in long int  is that it would help to get the ip details like contry and location within its range.

Any IP address is divided into 4 parts. generally each parts has different weightage.

To calculate IP number for any IP address:

IP Number = 16777216 * A + 65536 * B + 256 * C + D

This way we can also get range of IP address.

so if we have IP address say 74.125.236.80 than 
IP Number = 16777216 * 74 + 65536 * 125 + 256 * 236 + 80 =  132406480

I have made a function to calcualte above IP number in PHP, hope its helpful

 Function To get  IP Number from IP Address to in PHP

function ip2numer($ipaddress=''){
      if ($ipaddress == "") {
         return 0;
     } else {
         $ips = split ("\.", "$ipaddress");
          return ($ips[3] + $ips[2] * 256 + $ips[1] * 65536 + $ips[0] *16777216);
     }
}

No comments:

Post a Comment