Mysql 中 IP地址 和 int數字 格式互相轉換



在 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]>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章