I have a need to store both IPv6 and IPv4 addresses in such a way they can be ordered and searched in a SQL Server DB more or less using CIDR notation. I'm intending to use binary(16), with IPv4 encoded as IPv4-mapped-IPv6 so there is one single consistent representation of any one IP address. I can derive the appropriate network masks in binary form to supply to the query. But SQL Server can only perform bitwise operations when one operand is a numeric. I apparently cannot do a bitwise '&' with a binary(16) and a 128 bit value.
I realize I can read each row and do this in code, but I need this search to happen in the DB since there are a few million IPs to search through. I've seen most of the posts on "storing" and converting between binary and text. But those don't address my question. My question is more around binary searching of binary(16).
What is the best way to effect a CIDR search over binary(16) fields in SQL Server?