Mysql: 从二进制 ip 和子网中获取 IPv6 二进制网络掩码

Mysql: get IPv6 binary net mask from binary ip and subnet

我有一个 table 将 IPv6 地址存储为 BINARY(16) 并将子网存储为 INT(3)

我认为通过以下操作获取网络掩码会很简单:

SELECT ~INET6_ATON('::') << (128 - subnet);

但是这个 returns 零,实际上当我在二进制字符串上使用它们时,所有按位运算符似乎都提供整数结果:-(

我正在使用 10.1.30-MariaDB

+-----------------+
| VERSION()       |
+-----------------+
| 10.1.30-MariaDB |
+-----------------+

非常感谢任何帮助。

编辑:我完全误解了 Maria 的版本字符串,抱歉 :-(

5.5 中的位操作仅限于 64 位。 (8.0放宽了限制。 5.5 已经很老了。如果升级,要么转储并重新加载,要么分 3 步升级:5.5->5.6->5.7->8.0)

您可能想要 转变 >>。或者 (1 << amt) - 1。示例(仅使用 64 位算术):

SELECT HEX(~((1 << 8) - 1)); --> FFFFFFFFFFFFFF00

某些 128 位操作在 http://mysql.rjweb.org/doc.php/ipranges 的“IPv6 参考实现”link 中可用。没有“转移”功能,但您可以调整这些技术(使用 HEX())来实现您的目的。它确实有 add/subtract 1 to/from 一个 IPv6 值。这对于某些掩码构建和掩码操作很方便。

如果您想解释一下您将如何处理 SELECT 的结果,我或许可以为您提供更多答案。

(在 5.7.11 发行说明中找到):

Bit functions and operators comprise BIT_COUNT(), BIT_AND(), BIT_OR(), BIT_XOR(), &, |, ^, ~, <<, and >>. Currently, bit functions and operators require BIGINT (64-bit integer) arguments and return BIGINT values, so they have a maximum range of 64 bits. Arguments of other types are converted to BIGINT and truncation might occur.

An extension for MySQL 8.0 changes this cast-to-BIGINT behavior: Bit functions and operators permit binary string type arguments (BINARY, VARBINARY, and the BLOB types), enabling them to take arguments and produce return values larger than 64 bits. Consequently, bit operations on binary string arguments in MySQL 5.7 might produce different results in MySQL 8.0. To provide advance notice about this potential change in behavior, the server now produces warnings for bit operations for which binary string arguments are not converted to integer in MySQL 8.0. These warnings afford an opportunity to rewrite affected statements. To explicitly produce MySQL 5.7 behavior in a way that will not change after an upgrade to 8.0, cast bit-operation binary string arguments to convert them to integer. For more information and examples, see Bit Functions and Operators.