How to save space for mysql IP address storage: bitsCN.com
How to save space for IP address storage in mysql
As a developer, when you are using mysql to store your database, you will definitely consider using the most appropriate field type to create a database table.
However, if one of your statements writes ip varchar (15) not null default ''comment' user ip Address ',
You have not considered it. In fact, there is a more space-saving way to store users' IP addresses. (This is a variable, but for most Chinese IP addresses, it is generally 10 bytes or more ).
In fact, mysql has special fields and functions to access the user's IP address, that is, int unsigned. you are not mistaken, that is, there is no matching int type.
You can:
SELECT INET_ATON ('192. 168.23.4 ');
The value of this IP address is 3232241412.
You can also:
SELECT INET_NTOA (3232241412 );
The IP address corresponding to this value is 192.168.23.4.
Because they all follow a conversion algorithm:
A * 256*256*256 + B * 256*256 + C * 256 + D algorithm
The following provides a rough JAVA method to convert an IP address to a long one:
Public static long ipToLong (String strIp) throws Exception {
Long [] ip = new long [4];
// First locate the. position in the IP address string
Int position1 = strIp. indexOf (".");
Int position2 = strIp. indexOf (".", position1 + 1 );
Int position3 = strIp. indexOf (".", position2 + 1 );
// Convert the string between each. to an integer.
Ip [0] = Long. parseLong (strIp. substring (0, position1 ));
Ip [1] = Long. parseLong (strIp. substring (position1 + 1, position2 ));
Ip [2] = Long. parseLong (strIp. substring (position2 + 1, position3 ));
Ip [3] = Long. parseLong (strIp. substring (position3 + 1 ));
Return (ip [0] <24) + (ip [1] <16) + (ip [2] <8) + ip [3];
}
Then we provide a rough JAVA method to convert long into an IP string:
Public static String longToIP (long longIp ){
StringBuffer sb = new StringBuffer ("");
// Shifts the value of 24 digits to the right.
Sb. append (String. valueOf (longIp >>> 24 )));
Sb. append (".");
// Move the height of 8 to 0, and then shift the right to 16
Sb. append (String. valueOf (longIp & 0x00FFFFFF) >>> 16 ));
Sb. append (".");
// Change the height of 16 to 0, and then shift the right to 8 places
Sb. append (String. valueOf (longIp & 0x0000FFFF) >>> 8 ));
Sb. append (".");
// Set the height to 24 and 0
Sb. append (String. valueOf (longIp & 0x000000FF )));
Return sb. toString ();
}
BitsCN.com