Converting a normal IP Address to IP Long/decimal Format?

May 17, 08 by the programmer

IP addresses are expressed in dotted-decimal format - basically 4 sets of numbers from 0 to 255 seperated by periods

Another way of expressing an IP address is in a Long or Decimal 10 digit number format.

The decimal representation of the IP address is used because it is very easy to compare ranges of ip adresses that way.

So instead of comparing 192.168.1.1 to 192.168.1.255

it is much easier to compare 3232235777 to 3232236031

How is the decimal IP number generated from an IP address in a dotted format?

We will convert the IP address 192.168.0.1 from a dotted format to a decimal 10 digit format.

A.B.C.D = D + (C * 256) + (B * 256 * 256) + (A * 256 * 256 * 256) =

192.168.0.1 = 1 + (0 * 256) + (168 * 256 * 256) + (192 * 256 * 256 * 256) = 3232235521

This is a PHP function that will do that for you.

function ip_address_to_number($IPaddress) {

if ($IPaddress == “”) {

return 0;

} else {

$ips = split (\., “$IPaddress”);

return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);

}

}

Wait wait…

There is a much easier way of doing that in PHP. There is a already built in function in php just for that it’s called ip2long(). Check it out.

This applies only for IP v4 IP addresses

Have a nice conversion :)

Add your comment

2 responses for this post

  1. ken Says:

    There is also a long2ip() function in PHP :)

    Also, when working with IP’s, I’ll chip in that MYSQL (and probably other DB’s) have native functions that do the same thing, making things very easy on the backend for ip-based operations, i.e. INET_NTOA (number-to-address) and INET_ATON (address-to-number)…

    SELECT id, INET_NTOA(ip) WHERE ip = INET_ATON(’127.0.0.1′)

  2. ken Says:

    Well, my example is retarded, but you get the point. Perhaps this would be better:

    SELECT id, INET_NTOA(ip) WHERE ip >= INET_ATON(’192.168.0.0′) AND ip <= INET_ATON(’192.168.255.255′)

Leave a Reply