使用 mysql 查询从 IP 地址和掩码计算子网

Calculate subnet from IP Address and Mask using mysql query

如果我使用 mysql 有 IP 地址和掩码,是否可以计算子网?我知道在 php 中执行此操作,正在寻找在 mysql 中执行此操作的方法。我不是在寻找 cidr

My example data

ip address: 10.196.73.249
mask:29

如果您在 PHP 中已经知道如何执行此操作,那么数学对您来说应该不会太令人惊讶,只是 IP 地址和子网掩码。

使用 MySQL 的 INET_ATON() function to get the IP address into a number; this is equivalent to PHP's ip2long() function. To create the mask, use the REPEAT() function to put the requisite number of ones, and also to fill the rest of the string with zeroes. CONV() changes that binary string to decimal so we can do the math, and then a final INET_NTOA() 将其恢复为 IP 地址形式。

SET @IP='10.196.73.249';
SET @CIDR='29';
SELECT INET_NTOA(
    INET_ATON(@IP) &
    CONV(CONCAT(REPEAT(1, @CIDR), REPEAT(0, 32 - @CIDR)), 2, 10)
) AS network;

存储程序的实现方法如下:

CREATE FUNCTION get_network (ipadd VARCHAR(15), mask VARCHAR(2)) RETURNS VARCHAR(15)
RETURN INET_NTOA(
    INET_ATON(ipadd) &
    CONV(CONCAT(REPEAT(1, mask), REPEAT(0, 32 - mask)), 2, 10)
);

可以这样调用:

root@localhost [test]> SELECT get_network("192.168.242.234", "20");
+--------------------------------------+
| get_network("192.168.242.234", "20") |
+--------------------------------------+
| 192.168.240.0                        |
+--------------------------------------+
1 row in set (0.00 sec)