In development, it is often necessary to convert the IP address into an integer to save, which is not only conducive to indexing, and originally required 15 bytes of storage space,
It can be stored with only 4 bytes after conversion. However, because Ip2long only support IPv4, so this article is based on the IPv4 to explain
1, using PHP's built-in function Ip2long ()
$ip = ' 192.0.34.166 ';
echo Ip2long ($IP);
Results obtained-1073732954
The reason is that the function of the Ip2long conversion is signed with a maximum value of 2147483647
Once it is over, it will become negative, and the solution will be followed by
2, write your own function to convert
function Ip2int ($IP) {
Divide the IP into four segments, $ip 1, $ip 2, $ip 3, $ip 4
List ($ip 1, $ip 2, $ip 3, $ip 4) =explode (".", $ip);
Then the first paragraph is multiplied by 256 of three, the second is multiplied by 256 squared, the third segment multiplied by 256,pow is the exponential expression
Return $ip 1*pow (256,3) + $ip 2*pow (256,2) + $ip 3*256+ $ip 4;
}
echo Ip2int ($IP); (two functions get the same result)
Results obtained in 3221234342;
This is one way to avoid negative numbers, but using functions is a little cumbersome
Then we use LONG2IP to convert to the data values we just converted.
$ip 1 = long2ip (Ip2long ($IP));//use built-in functions Ip2long
echo $ipint;//192.0.34.166
$ip 2 = ip2int ($IP);//Use the above custom function
echo $ipint;//192.0.34.166
The result is the same, and although the result is the same, we need to store the address into the database after converting it into an integer.
Negative values are not friendly, so you need to improve
Improvement methods
$ipint = sprintf ('%u ', Ip2long ($IP));//%u formatted as an unsigned decimal number
echo $ipint;//3221234342
So the result won't be a problem.
This article is from the "Good Day" blog, please make sure to keep this source http://tianhaoblog.blog.51cto.com/6467511/1684356
Explanation of Ip2long,long2ip and the solution of negative number of conversion integral type