如何在 MySQL 中使用 INET_ATON 对 IP 地址进行通配符搜索?

Tro*_*gan 2 php mysql inet-aton ip2long

我发现这种使用 INET_ATON 将 IP 地址作为整数存储在 MySQL 数据库中的方法:https ://stackoverflow.com/a/5133610/4491952

由于 IPv4 地址的长度为 4 个字节,因此您可以使用正好为 4 个字节的INT( UNSIGNED)

`ipv4` INT UNSIGNED
Run Code Online (Sandbox Code Playgroud)

INET_ATONINET_NTOA它们转换:

INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));
SELECT INET_NTOA(`ipv4`) FROM `table`;
Run Code Online (Sandbox Code Playgroud)

对于 IPv6 地址,您可以改用 a BINARY

`ipv6` BINARY(16)
Run Code Online (Sandbox Code Playgroud)

并使用PHP 的inet_ptonandinet_ntop进行转换:

'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);
Run Code Online (Sandbox Code Playgroud)

但是如何使用 INET_ATON 和 PHP 的 ip2long 函数进行通配符搜索,例如 192.168.%?

小智 5

MySQL 提供的一个巧妙的技巧是位移。您可以使用它来查看 ip 是否包含在以 cidr 表示法编写的地址块中。您可以使用此方法将您的地址视为 XXXX/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)
Run Code Online (Sandbox Code Playgroud)

查看 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)
Run Code Online (Sandbox Code Playgroud)