Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

1 Answers

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)
like image 170
Laurenz Albe Avatar answered Jan 19 '26 19:01

Laurenz Albe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!