How to convert an IP network address protocol address with four fields separated by dots into an integer? There is such a function ip2long in PHP. For example,
can be converted into a positive integer. And the result obtained can be converted back to the original IP address normally using long2ip. You can also use ip2long to verify whether an IP is valid, such as
When saving IP data in a database (MySQL), we are used to using the ip2long function to generate an integer and then storing it in an int(11) type field. However, on different system platforms, the ip2long function obtains The values are different, so it may cause errors when reading data from the database and using long2ip to get the IP. Let’s talk about the situation we encountered:
We use an int (11) type (range -2147483648 -2147483647 ) to save the result of processing an ip address with ip2long. For example, if the ip is '202.105.77.179', then the result obtained on a 32-bit machine is: -899068493, but on a 64-bit machine, 3395898803 is obtained. Then put it When writing to the database, since it exceeds the range of int(11), the result on the 64-bit machine is saved as the maximum value of int(11): 2147483647. So when it is taken out from the database, the wrong result is obtained. Get the IP address "127.255.255.255".
There are many solutions. For example, you can use mysql functions: INET_ATON and INET_NTOA to process the IP address; or change the field that saves the IP address to the bigint type, so that it can be used on a 64-bit machine. Although 3395898803 is saved, the correct result can still be obtained by using the long2ip function.