3

我的 SQL-Server 数据库将 IP 网络掩码存储为二进制文件。我需要一种将这些与给定 IP 匹配的方法

例如,192.168.21.5是存储在数据库中的网络掩码的一部分吗?

的二进制表示192.168.21.5

11000000.10101000.00010101.00000101 (without the dots)

存储在数据库中的网络掩码是:binary(4) 和一个 tinyint 字段:

11000000.10101000.00010101.00000000 / 24

(这将是:)192.168.21.0 /24所以,前 24 位192.168.21.5必须匹配数据库中的记录。

我如何只检查n二进制字段的第一位(类似于LEFT(text, 24))?

有什么聪明的方法可以做到这一点,也许是按位AND

4

4 回答 4

7
declare @address binary(4) -- goal is to check if this address
declare @network binary(4) -- is in this network
declare @netmask tinyint   -- with this netmask in /NN format

set @address = 0xC0A81505 -- 192.168.21.5
set @network = 0xC0A81500 -- 192.168.21.0
set @netmask = 24

select
  'address matches network/netmask'
where
  0 = (
      cast(@address as int) ^ cast(@network as int))
      &
      ~(power(2, 32 - @netmask) - 1)
      )

@netmask必须在 2 到 32 之间。

于 2009-12-30T23:28:25.110 回答
1

192.168.21.5 XOR netmask (192.168.21.0) AND 255.255.255.0(您只需要前 24 位)应该全部0在“匹配”IP 上。

于 2009-12-30T15:08:53.507 回答
0

这个条件做到了:

(0xffffffff - POWER(2, 32 - bits) + 1) & CAST(ip AS int) = CAST(netmask AS int)
于 2009-12-30T15:12:48.460 回答
0

如果您希望它使用掩码 0 或 1 位,那么您需要将 power(2, 32 - @netmask) 更改为 power(cast(2 as bigint), 32 - @netmask) 再见

于 2018-03-28T11:26:36.807 回答