Search code examples
postgresqlippostgresql-9.4cidr

How can I get a CIDR from two IPs in PostgreSQL?


In PostgreSQL, I can get the upper and lower boundary of a CIDR-range, like below.

But how can I get the CIDR from two IP addresses (by SQL) ?
e.g.

input "192.168.0.0";"192.168.255.255"
output "192.168.0.0/16"

SELECT 
     network
    ,network::cidr 
    -- http://technobytz.com/ip-address-data-types-postgresql.html
    --,netmask(network::cidr) AS nm  
    --,~netmask(network::cidr) AS nnm
    ,host(network::cidr) AS lower 
    ,host(broadcast(network::cidr)) AS upper -- broadcast: last address in the range
    ,family(network::cidr) as fam  -- IPv4, IPv6
    ,masklen(network::cidr) as masklen
FROM 
(
          SELECT CAST('192.168.1.1/32' AS varchar(100)) as network 
    UNION SELECT CAST('192.168.0.0/16' AS varchar(100)) as network 
    --UNION SELECT CAST('192.168.0.1/16' AS varchar(100)) as network 

) AS tempT

Solution

  • I think you are looking for inet_merge:

    test=> SELECT inet_merge('192.168.0.0', '192.168.128.255');
    ┌────────────────┐
    │   inet_merge   │
    ├────────────────┤
    │ 192.168.0.0/16 │
    └────────────────┘
    (1 row)