检查ipv6是否在范围内

时间:2017-02-23 11:48:13

标签: mysql mariadb ipv6

我有maxmind的ipv6数据。这是我当前的表格(包含样本数据):

+---------------+------------+
|    network    | geoname_id |
+---------------+------------+
| 2001:208::/32 |        123 |
| 2001:218::/32 |       4312 |
+---------------+------------+

使用their converter,我可以创建network_start_ipnetwork_last_ip列:

+------------------+----------------------------------------+------------+
| network_start_ip |            network_last_ip             | geoname_id |
+------------------+----------------------------------------+------------+
| 2001:200::       | 2001:200:ffff:ffff:ffff:ffff:ffff:ffff |        123 |
| 2001:208::       | 2001:208:ffff:ffff:ffff:ffff:ffff:ffff |       4312 |
+------------------+----------------------------------------+------------+

我期待这样的东西能够起作用(即使它可能比其他方法慢):

SELECT b.geoname_id FROM blocks b 
WHERE HEX(INET6_ATON('2001:201:ffff:ffff:ffff:ffff:ffff:ffff')) BETWEEN HEX(b.network_start_ip) AND HEX(b.network_last_ip)

那么,我错过了什么?另外,存储ipv6地址(范围)的最佳方法是什么

谢谢

1 个答案:

答案 0 :(得分:2)

以下是我的工作方式:

  1. 创建了具有相同列的另一个表,但network_start_ipnetwork_last_ipVARBINARY(16)
  2. 使用此语句填充该表:INSERT INTO blocks SELECT INET6_ATON(b2.network_start_ip), INET6_ATON(b2.network_last_ip), b2.geoname_id FROM blocks_copy b2;
  3. 然后,要检查IPv6地址是否在范围内,我只需要运行此查询:SELECT geoname_id FROM blocks b WHERE INET6_ATON('2a01:4ff:ffff:ffff::ffff') BETWEEN b.network_start_ip AND b.network_last_ip