I basically have a 2 column table with an IP subnet as the key/index and a description as the value. For example:
10.20.30.0/30 "Subnet 1"
I need to write a REST service that will return the description of the subnet containing the given IP address, or list of subnets if the IP address matches more than one.
At first, I thought I would simply use a backend database (Postgres) and expand all the subnets because I wasn't dealing with large amounts of data. So the above example would be expanded to:
10.20.30.0 "Subnet 1"
10.20.30.1 "Subnet 1"
10.20.30.2 "Subnet 1"
10.20.30.3 "Subnet 1"
This is inefficient in terms of storage, especially as subnets get large. However, it is quick and easy to do, and existing databases have really efficient ways to lookup IP addresses as indexes, so this was my first idea. I am mostly concerned with lookup efficiency since I will have about 1 million entries in my DB.
However, I found out I also have requirements for IPv6, and the subnets involved are HUGE. This means I no longer have the option of expanding all the subnets.
Before I go ahead and start writing my custom REST API I wanted to know if POSTGRES queries for checking IP addresses using subnets as an index are efficient. The check is not trivial and I don't know how it would be done internally to maintain efficiency.
Does anyone know how POSTGRES checks for IP addresses in tables indexed by subnet?
EDIT: Here is an example of IP address lookup in POSTGRES that I am talking about (using online https://extendsclass.com/postgresql-online.html)
drop table ipdesc;
create table ipdesc (addr inet, category varchar(20));
insert into ipdesc (addr, category) values ('10.10.10.0/24', 'tens');
insert into ipdesc (addr, category) values ('20.20.20.0/24', 'twenties');
insert into ipdesc (addr, category) values ('50.50.50.0/24', 'fifties');
insert into ipdesc (addr, category) values ('50.50.50.0/30', 'sub-fifty');
select * from ipdesc where inet '50.50.50.1' << addr;
Results:
addr category
---- --------
50.50.50.0/24 fifties
50.50.50.0/30 sub-fifty
Thanks!