SQL Server: Store and Retrieve IP Address

We can store IP addresses in SQL Server in a varchar column. However to retrieve IP address for a specific range, we need to split each part and compare it.

Consider the following table:

SQL Server IP Address

Suppose we want to retrieve all the IP addresses that fall in the range from 192.168.120.120
to 192.168.200.255. The following query will retrieve these IP addresses:

SQL Server IP Address

Here’s the same query for you to try out:

declare @from_ip varchar(20), @to_ip varchar(20)

select @from_ip='192.168.120.120',@to_ip='192.168.200.255'

select * from @t
where
parsename(Ip_address,4)*1>= parsename(@from_ip ,4)*1 and
parsename(Ip_address,4)*1<= parsename(@to_ip ,4)*1
and
parsename(Ip_address,3)*1>= parsename(@from_ip ,3)*1 and
parsename(Ip_address,3)*1<= parsename(@to_ip ,3)*1
and
parsename(Ip_address,2)*1>= parsename(@from_ip ,2)*1 and
parsename(Ip_address,2)*1<= parsename(@to_ip ,2)*1
and
parsename(Ip_address,1)*1>= parsename(@from_ip ,1)*1 and
parsename(Ip_address,1)*1<= parsename(@to_ip ,1)*1

In the query shown above, the Parsename function is used split IP addresses based on a dot (.) . As the IP address is stored in a varchar data type, we need to convert to integer to do calculations. Multiplying it by 1 will convert the varchar number to Integer

OUTPUT

5 comments:

  1. You should store your IP addresses as integers in the database. That way "from 192.168.120.120 to 192.168.200.255" becomes "from 3232266360 to 3232286975".

    ReplyDelete
  2. I don't think your method scales very well. You also cannot convert your method to a function as PARSENAME is not a deterministic function in sql.

    Try this for multiple alternatives.

    http://www.stev.org/post/2011/02/17/MSSQL-Convert-IP-To-big-int.aspx

    ReplyDelete
  3. James, non deterministics functions like parsename, getdate() as re allowed in user defined function from version 2005 onwards

    ReplyDelete
  4. Yeah sorry they are. However you cannot use a non deterministic function in a pre computed field what is really what I mean to say.

    If you have a function that is deterministic you can then create a computed field on the ip address and add an index to it. Thus speeding the range searches by massive amounts

    ReplyDelete
  5. For ipv4:
    https://monparasanjay.wordpress.com/2015/01/22/split-ip-address-from-given-range/

    ReplyDelete