如何从PostgreSQL中的两个IP获取CIDR?

时间:2016-11-18 12:32:50

标签: postgresql ip postgresql-9.4 cidr

在PostgreSQL中,我可以获得CIDR范围的上下边界,如下所示。

但是如何从两个IP地址(通过SQL)获取CIDR?
例如

  

输入“192.168.0.0”;“192.168.255.255”
  输出“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

1 个答案:

答案 0 :(得分:4)

我认为您正在寻找inet_merge

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