检查 ipv6 是否在范围内

2022-01-15 00:00:00 ipv6 mariadb mysql

我有 maxmind 的 ipv6 数据.这是我当前的表格(带有示例数据):

I have the maxmind's ipv6 data. Here's my current table (with sample data):

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

使用 他们的转换器,我可以创建一个 network_start_ipnetwork_last_ip 列:

Using their converter, I can create a network_start_ipand network_last_ip columns:

+------------------+----------------------------------------+------------+
| 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 |
+------------------+----------------------------------------+------------+

我期待这样的事情会起作用(即使它可能会比其他方法慢):

I was expecting that something like this would work (even though it would probably be slower than other methods):

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 地址(范围)的最佳方式是什么

So, what am I missing? Also, what is the best way to store ipv6 addresses (ranges)

谢谢

推荐答案

这是我的工作方式:

  1. 创建了另一个具有相同列的表,但 network_start_ipnetwork_last_ipVARBINARY(16)
  2. 使用以下语句填充该表:INSERT INTO 块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 bWHERE INET6_ATON('2a01:4ff:ffff:ffff::ffff') 在 b.network_start_ip 和 b.network_last_ip 之间
  1. Created another table with the same columns, but network_start_ip and network_last_ip are VARBINARY(16)
  2. Populated that table with this statement: INSERT INTO blocks SELECT INET6_ATON(b2.network_start_ip), INET6_ATON(b2.network_last_ip), b2.geoname_id FROM blocks_copy b2;
  3. Then, to check if the IPv6 address is in the range, I just need to run this query: SELECT geoname_id FROM blocks b WHERE INET6_ATON('2a01:4ff:ffff:ffff::ffff') BETWEEN b.network_start_ip AND b.network_last_ip

相关文章