7

If we have an ip address as below:

127.0.0.1

Does both functions convert the ip address to the same number, or do they differ and have different result?

Alireza
  • 6,497
  • 13
  • 59
  • 132

2 Answers2

11

They are almost exactly the same. ip2long sometimes returns a negative value because PHP uses signed numbers for valuation, while MySQL uses unsigned.

Both are evaluated as x*(2^24) + y*(2^16) + z*(2^8) + w*(2^0), but in PHP, due to the long being signed, will show negative values for certain IP addresses.

For signed long, the range is 
(2^31) - 1 = −2,147,483,648 to +2,147,483,647

So, addresses while translate to over +2,147,483,647 will wrap around and give negative values.

ip2long("254.254.254.254"); // -16843010

This link describes this in detail.

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
  • If I gave just the first oct, will those functions accept? I need it for converting GEOLocation countries. for example 127 to int from 127.0.0.1? Thanks. – Alireza Jul 19 '12 at 08:40
  • ip2long requires that the input be a `string containing an (IPv4) Internet Protocol dotted address`. While INET_ATON() does not throw errors, it might/might not return the right value. `127` may be translated to `127.0.0.0`, not `127.0.0.1`. [More Info](http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_inet-aton) – Anirudh Ramanathan Jul 19 '12 at 08:50
7

in short, no, but this function is:

function ipv4touint($ipv4){
    return sprintf('%u',ip2long($ipv4));
}
hanshenrik
  • 19,904
  • 4
  • 43
  • 89
  • 1
    I will explain why this is a correct answer. In the accepted answer it's mentioned that on 32-bit platforms `ip2long` can return negative number. The trick with `sprintf` will turn negative numbers into correct positive. Btw it's recommended workaround from PHP manual. – Stalinko Nov 02 '16 at 05:24