Tuesday, January 26, 2010

[Level 3] Enhance to save ip address in MySQL

What data type will you define the column for ip values.
Usually I got the answer is char(15).
But should we really have to set char(15)?
Any way to reduce the data size for saving ip data?
Yes, you can use "Int Unsigned" data type to save it!
Int??? Yes just Int!
At the same time you have to use another two stored routine for it, called
"inet_aton()" and "inet_ntoa()".
inet_aton() is the routine to convert the ip address from domain to integer.
inet_ntoa() is the routine to convert the integer to ip address domain value.

my sample as the following:

mysql> create table ip_table (ipaddr int unsigned); Query OK, 0 rows affected (0.01 sec)
mysql> insert into ip_table values (inet_aton('')), (inet_aton(''));
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select inet_ntoa(ipaddr) from ip_table;
| inet_ntoa(ipaddr) |
|         |
|     |
2 rows in set (0.00 sec)

Wish this helps.

Stanley Huang