Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres Check if IP (inet) is IN a list of IP Ranges

I want to check if an IP exists in a range of ranges, eg: SELECT * FROM ip_address WHERE ip IN (<list of ip ranges>)

Postgresql documentation states to use the << operator to check if an IP is contained within a single IP Range, eg: inet '192.168.1.5' << inet '192.168.1/24', but I'm not sure how to use it on a list of ranges without having to construct an OR chain of <<'s.

like image 363
Eric Zhang Avatar asked Jul 24 '14 21:07

Eric Zhang


People also ask

How many IP addresses are in a range?

For IPv4, this pool is 32-bits (232) in size and contains 4,294,967,296 IPv4 addresses. The IPv6 address space is 128-bits (2128) in size, containing 340,282,366,920,938,463,463,374,607,431,768,211,456 IPv6 addresses. A bit is a digit in the binary numeral system, the basic unit for storing information.

What is INET in postgresql?

inet. The inet type holds an IPv4 or IPv6 host address, and optionally its subnet, all in one field. The subnet is represented by the number of network address bits present in the host address (the “netmask”). If the netmask is 32 and the address is IPv4, then the value does not indicate a subnet, only a single host.


1 Answers

select inet '192.168.1.5' << any (array['192.168.1/24', '10/8']::inet[]);
 ?column? 
----------
 t

http://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN18486

like image 71
Clodoaldo Neto Avatar answered Oct 19 '22 16:10

Clodoaldo Neto