T-Sql:检查IP是否与网络掩码匹配

rei*_*ard 2 t-sql bit-manipulation ip-address netmask

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

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

二进制表示192.168.21.5:

11000000.10101000.00010101.00000101 (without the dots)
Run Code Online (Sandbox Code Playgroud)

存储在DB中的网络掩码是:binary(4)和tinyint字段:

11000000.10101000.00010101.00000000 / 24
Run Code Online (Sandbox Code Playgroud)

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

我怎么才检查n二进制字段的第一位(类似于LEFT(text, 24))?

有没有聪明的方法来做到这一点,也许是按位AND

Vad*_* K. 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)
      )
Run Code Online (Sandbox Code Playgroud)

@netmask 必须在2到32之间.