在 Mysql 中,
我们通常用 int数字形式 来存储 IP 地址(原因戳 《 将 IP地址 以 int类型 存储到 Mysql 有什么好处?》 ),
但是,
在 select 出来查看使用的时候,
又希望转成可读性较好的 IP地址形式,
那么,在 Mysql 中,有什么简便的办法满足这个需求呢?
Mysql 有两个内置函数,可以用于互相转换 ip地址 和 int数字 :
inet_aton: // 将 ip地址 转换成 int数字
inet_ntoa: // 将 int数字 转换成 ip地址
举几个例子,看看用法:
MySQL [test_log]> select ip from test_log_10 limit 1;
+-----------+
| ip |
+-----------+
| 318898187 |
+-----------+
1 row in set (0.00 sec)
MySQL [test_log]> select inet_ntoa(ip) from test_log_10 limit 1;
+---------------+
| inet_ntoa(ip) |
+---------------+
| 19.2.0.11 |
+---------------+
1 row in set (0.00 sec)
MySQL [test_log]> select inet_aton(inet_ntoa(ip)) from test_log_10 limit 1;
+--------------------------+
| inet_aton(inet_ntoa(ip)) |
+--------------------------+
| 318898187 |
+--------------------------+
1 row in set (0.01 sec)
MySQL [shell_log]>
这个转换,本质上是 IP 地址的每一小段都转为二进制拼接起来,
然后将这个 32 位的二进制数字再转为 10 进制,
验证效果如下:
MySQL [test_log]> select concat(bin(19),lpad(bin(2),8,0),lpad(bin(0),8,0),lpad(bin(11),8,0));
+---------------------------------------------------------------------+
| concat(bin(19),lpad(bin(2),8,0),lpad(bin(0),8,0),lpad(bin(11),8,0)) |
+---------------------------------------------------------------------+
| 10011000000100000000000001011 |
+---------------------------------------------------------------------+
1 row in set (0.00 sec)
MySQL [test_log]> select inet_aton('19.2.0.11' );
+-------------------------+
| inet_aton('19.2.0.11' ) |
+-------------------------+
| 318898187 |
+-------------------------+
1 row in set (0.00 sec)
MySQL [test_log]> select bin(inet_aton('19.2.0.11' ));
+-------------------------------+
| bin(inet_aton('19.2.0.11' )) |
+-------------------------------+
| 10011000000100000000000001011 |
+-------------------------------+
1 row in set (0.00 sec)
MySQL [test_log]>