Skip to content

Instantly share code, notes, and snippets.

@ninjarobot
Last active April 17, 2018 01:18
Show Gist options
  • Save ninjarobot/96f67a27b1fa9104ebfa66fce50116de to your computer and use it in GitHub Desktop.
Save ninjarobot/96f67a27b1fa9104ebfa66fce50116de to your computer and use it in GitHub Desktop.
Examples of using the cidr type from Postgres
-- Increment addresses, with increment of octet
select inet '192.168.0.1' + 256;

-- Increment addresses starting with a network
select cidr '192.168.100.128/25' + 256;

-- Get a cidr network address from shorthand
select cidr '10.1.2';

-- See if an address is within a subnet
select cidr '192.168.13.0/24' >> cidr '192.168.13.92'; -- true
select cidr '192.168.13.0/25' >> cidr '192.168.13.92'; -- true
select cidr '192.168.13.0/26' >> cidr '192.168.13.92'; -- false

-- Get broadcast address for a subnet
select broadcast(cidr '192.168.13/25');

-- Get an IPv6 address
select (cidr 'fe80::d6b7:45a0:bcac:e0b6');
-- See if an IPv6 address is within a subnet
select (cidr 'fe80:12e3:d6b7::0/64' >> cidr 'fe80:12e3:d6b7:45a0::e0b6' );

-- See if an address is IPv4 or IPv6 (this returns 4)
select (family (cidr '10.0.1.23'));

-- Get the subnet prefix length for a network.
select masklen( cidr '10.0.1.0');

-- Subtract addresses to get the number of IP's between them
select cidr '192.168.1.43' - cidr '192.168.1.17';

-- Get number of IPv6 addresses in a range
select (cidr 'fe80:12e3:d6b7:45a0::e0b6' - cidr 'fe80:12e3:d6b7:45a0::0' );

-- Get the upper IPv4 address needed to have 1097 addresses
select (inet '192.168.1.43' + 1097);

select (cidr 'fe80::9a8f:a2ab:f8f4:ce73');
-- Get an IPv6 network address by applying a prefix length to a network address
select set_masklen(cidr 'fe80::9a8f:a2ab:f8f4:ce73', 102);

-- Get broadcast address for IPv6 network
select broadcast(cidr 'fe80:db8:1234::/48');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment