MySQL 提供的一项巧妙技巧是位移位。您可以使用它来查看 IP 是否包含在以 cidr 表示法编写的地址块中。您可以使用此方法将您的地址视为 X.X.X.X/16 cidr 块。
set @cidr_block:='10.20.30.40/16';
select inet_ntoa(inet_aton(substring_index(@cidr_block,'/',1))>>(32-substring_index(@cidr_block,'/',-1))<<(32-substring_index(@cidr_block,'/',-1))) as first_ip,
inet_aton(substring_index(@cidr_block,'/',1))>>(32-substring_index(@cidr_block,'/',-1))<<(32-substring_index(@cidr_block,'/',-1)) as first_ip_num,
inet_ntoa((((inet_aton(substring_index(@cidr_block,'/',1))>>(32-substring_index(@cidr_block,'/',-1)))+1)<<(32-substring_index(@cidr_block,'/',-1)))-1) as last_ip,
(((inet_aton(substring_index(@cidr_block,'/',1))>>(32-substring_index(@cidr_block,'/',-1)))+1)<<(32-substring_index(@cidr_block,'/',-1)))-1 as last_ip_num
;
+-----------+--------------+---------------+-------------+
| first_ip | first_ip_num | last_ip | last_ip_num |
+-----------+--------------+---------------+-------------+
| 10.20.0.0 | 169082880 | 10.20.255.255 | 169148415 |
+-----------+--------------+---------------+-------------+
1 row in set (0.00 sec)
查看 ip 是否在地址块中的快捷方式 - 只需筛选 cidr 地址和 ip 即可查看它们是否相同。当然,如果应用于存储的值,这将是表扫描。
select inet_aton('127.0.0.1')>>16 = inet_aton('127.0.10.20')>>16 as `1 = true`;
+----------+
| 1 = true |
+----------+
| 1 |
+----------+
1 row in set (0.00 sec)
select inet_aton('127.0.0.1')>>16 = inet_aton('127.10.10.20')>>16 as `0 = false`;
+-----------+
| 0 = false |
+-----------+
| 0 |
+-----------+
1 row in set (0.00 sec)