Search code examples
postgresqlipv6postgresql-9.2

Storing IPv6 ranges in PostgreSQL


In 9.2, new range functionality was added. How do I create a table with IPv6 ranges fields?
Do I need to create new type?
An example / link will be appreciated.


Solution

  • PostgreSQL already supports type CIDR, which can store ranges for both IPv4 and IPv6. The only catch that these ranges cannot be like 1.2.3.1-1.2.3.10 for IPv4 or ::5:1-::5-10, but only like 1.2.3/28 or 2001:0:0:5::0/64 - typical for classless subnet declaration.

    If you want more flexibility than CIDR, and want to have true arbitrary INET ranges, there is ip4r extension what offers these ready to use. It is included by default in some Ubuntu versions (for example it is included in Ubuntu 12.10).

    Don't be fooled by ip4r name: it supports both IPv4 and IPv6 since version 2.0. It also supports typical range operations that you would expect, like BETWEEN, <<= to check if IP belongs to range and some others. Read more here: README.ip4r.