PostgreSQL field data type for IPv4 addresses
The built-in cidr
and inet
types will do what you want and provide suitable operators:
regress=> SELECT '192.168.1.19'::inet << '192.168.1.0/24'::cidr; ?column? ---------- t(1 row)
See the PostgreSQL documentation on network datatype operators and functions and on the network datatypes.
Limited index support is provided for the cidr
and inet
types; in particular, 'address in range' type queries are turned into range queries at least where the address is a constant. See this (rather old) thread.
See also Chris's point re ip4r
.
http://www.postgresql.org/docs/current/static/datatype-net-types.html having field of inet
type it is only what you need.
The operators <<, <<=, >>, and >>= test for subnet inclusion.
I want to add that the built-in types are quite powerful, and that's where you should start. However if you need GIN indexing, check out http://pgfoundry.org/projects/ip4r/
A case for ip4r (why I started using it) might be if you need to store CIDR blocks and make sure that no block contains any other block. Since this requires GIN indexing, you have to go with ip4r rather than the built-in types.