IP4R
IPv4 and IPv6 types and range operations
The ip4r
extension provides data types and functions for working with IPv4 and IPv6 addresses and ranges. It’s particularly useful for network-related applications, IP-based access control, and geolocation services.
Your Nile database arrives with the ip4r
extension already enabled.
Data Types
The extension provides several data types:
ip4
- IPv4 addressip4r
- IPv4 rangeip6
- IPv6 addressip6r
- IPv6 rangeipaddress
- Can store either IPv4 or IPv6 addressiprange
- Can store either IPv4 or IPv6 range
Basic Usage
Here’s how to use the IP address types and operations:
IP Address Operations
The extension provides various operators for IP address manipulation and comparison:
Common Use Cases
IP-based Access Control
Network Range Analysis
Query Optimization
The extension supports GiST indexes for efficient range queries:
This index improves performance for these operators:
>>
(contains)>>=
(contains or equals)<<
(contained by)<<=
(contained by or equals)&&
(overlaps)
Performance Considerations
- GiST indexes significantly improve range query performance
- IP address operations are very efficient as they use native integer comparisons
- Range operations are optimized for both IPv4 and IPv6
- Indexes work well with both IP versions in the same column
Limitations
- Cannot mix IPv4 and IPv6 in range comparisons
- Some operations are version-specific (ip4 vs ip6)
- Maximum IPv4 range is /0 (0.0.0.0 to 255.255.255.255)
- Maximum IPv6 range is /0 (:: to ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff)
Alternative Approaches
For some use cases, you might want to consider:
- Using the built-in
inet
type for basic IP address storage - Using
cidr
type for network ranges without host bits - Using separate columns for IPv4 and IPv6 if operations are always version-specific
For more details, refer to the PostgreSQL documentation on network address types and the ip4r extension documentation.