[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>
mysql> insert into ip_table values (inet_aton('127.0.0.1')), (inet_aton('255.255.255.0'));
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

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

Wish this helps.

regards,
Stanley Huang

Comments

Popular posts from this blog

[Level 1] Rar tool for Solaris.

[Level 2] iif in Python