简体   繁体   中英

Find IP (IPv4 and IPv6) address between range

Question: Is it possible to search for values that are in between (ie, BETWEEN, greater than, and less than type math operators) each other when the data is stored in a VARBINARY data type?

Problem: I have a list of IP addresses (both IPv4 and IPv6) where I need to determine the geolocation of that IP address, which means I need to search between ranges.

Typically, this can be accomplished by converting the address to integer and then using the BETWEEN operator. However, with IPv6 effectively exceeding all numeric, decimal, and integer related data types, as of this posting, then it appears that I need to store the data in the VARBINARY data type.

I have not used this data type in the past, so I am not aware of how, or if it is even possible, to search between values. My searches online have not turned up any hits, so I am asking here.

Note: currently using SQL Server 2014, but will be migrating to SQL Server 2017 for this project.

Your approach is correct.

You can use VARBINARY operator for comparison.

Here is an approved answer in MSDN groups. But the link may be broken in future, so I am pasting the query also below.

Query:

DECLARE @b1 varbinary(16) = convert(varbinary(16), newid()),
        @b2 varbinary(16) = convert(varbinary(16), newid())
SELECT CASE WHEN @b1 > @b2 THEN '@b1 is bigger' ELSE '@b2 is bigger' END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM