DEV Community

Sadeed Ahmad
Sadeed Ahmad

Posted on

Network Address Data Types in PostgreSQL - Part 1

PostgreSQL provides multiple data types for storing IPv4, IPv6, and MAC addresses. Instead of using basic text types, it is better to use these specific types for storing network addresses. The reason being the fact that these data types provide error validation during input and offer dedicated operators and functions for manipulating them.

Image description

inet

The inet type can store both IPv4 and IPv6 host addresses, along with their subnets, within a single field. The subnet is defined by the number of network address bits included in the host address, "netmask."

In the case of IPv4 addresses with a netmask of 32, it signifies a single host rather than a subnet. For IPv6, the address length is fixed at 128 bits, resulting in a unique host address when all 128 bits are specified.

It is recommended to use the cidr type instead of inet if you want to store network addresses and not individual hosts.

cidr

The cidr type in PostgreSQL is designed to store specifications of IPv4 or IPv6 networks. The input and output formats follow the conventions of Classless Internet Domain Routing (CIDR). The format follows the pattern of "address/y," where "address" represents the lowest address of the network, expressed as an IPv4 or IPv6 address, and "y" indicates the number of bits in the netmask.

If the "y" value is not provided, it is calculated based on assumptions derived from the older classful network numbering system. However, the calculated value will always be large enough to encompass all the octets specified in the input. It is important to note that specifying network addresses with bits set to the right of the specified netmask is considered an error and should be avoided.

Image description

The important difference between inet and cidr data types is that inet accepts values with nonzero bits to the right of the netmask, whereas cidr does not.

Top comments (0)