mysql中IP地址的存储以及字符型和整型之间的互相转换
IP:如192.168.12.145,在存储时,若是采用varchar进行存储,存在两个主要缺点:
存储空间占用较大;
查询检索较慢;
解决方式:
存储时:将字符串类型的IP转换为整型进行存储;
查询时:将整型的IP转换为字符串;
Mysql自带的IP转换语句
inet_aton:将ip地址转换成数字型
inet_ntoa:将数字型转换成ip地址
示例1:
//使用inet_aton函数,将字符串IP转换为整型;
mysql> select inet_aton('73.115.134.73') as ip;
+------------+
| ip |
+------------+
| 1232307785 |
+------------+
//使用inet_ntoa函数,将整型IP转换为字符串;
mysql> select inet_ntoa(1232307785) as ip;
+---------------+
| ip |
+---------------+
| 73.115.134.73 |
+---------------+
示例2:
//不进行转换,查询结果为整型
mysql> select src_ip from natTable limit 5;
+------------+
| src_ip |
+------------+
| 1232307785 |
| 1232285337 |
| 1232323310 |
| 1232325234 |
| 1232326662 |
+------------+
//通过inet_ntoa函数进行转换,查询结果为IP格式的字符串
mysql> select inet_ntoa(src_ip) from natTable limit 5;
+-------------------+
| inet_ntoa(src_ip) |
+-------------------+
| 73.115.134.73 |
| 73.115.46.153 |
| 73.115.194.238 |
| 73.115.202.114 |
| 73.115.208.6 |
+-------------------+