Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ip2long() in PHP equal to INET_ATON() function in MySQL?

Tags:

php

mysql

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?

like image 744
Alireza Avatar asked Jul 19 '12 08:07

Alireza


2 Answers

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.

like image 188
Anirudh Ramanathan Avatar answered Oct 08 '22 05:10

Anirudh Ramanathan


in short, no, but this function is:

function ipv4touint($ipv4){
    return sprintf('%u',ip2long($ipv4));
}
like image 29
hanshenrik Avatar answered Oct 08 '22 03:10

hanshenrik