Implementation:ClickHouse ClickHouse IPv4andIPv6
| Knowledge Sources | |
|---|---|
| Domains | Networking, Data_Types |
| Last Updated | 2026-02-08 00:00 GMT |
Overview
Strong type definitions for IPv4 and IPv6 addresses that provide type safety and prevent accidental misuse.
Description
This header defines `IPv4` and `IPv6` as strong typedefs over `UInt32` and `UInt128` respectively, providing type-safe representations of IP addresses. Unlike raw integer types or strings, these types prevent accidental conversions or mixing of IPv4 and IPv6 addresses. The `IPv6` type includes comparison operators, while both types have custom hash functions for use in hash tables and maps.
The strong typedef pattern ensures that you cannot accidentally pass an IPv4 address where an IPv6 is expected, or use an IP address as a generic integer.
Usage
Use this implementation when you need to:
- Store IP addresses in a type-safe manner
- Prevent accidental mixing of IPv4 and IPv6 addresses
- Use IP addresses as keys in hash tables or maps
- Ensure compile-time type checking for network operations
- Represent IP addresses efficiently without string parsing overhead
Code Reference
Source Location
- Repository: ClickHouse
- File: base/base/IPv4andIPv6.h
- Lines: 1-56
Signature
struct IPv4 : StrongTypedef<UInt32, struct IPv4Tag> {
using StrongTypedef::StrongTypedef;
constexpr explicit IPv4(UInt64 value);
};
struct IPv6 : StrongTypedef<UInt128, struct IPv6Tag> {
using StrongTypedef::StrongTypedef;
bool operator<(const IPv6 & rhs) const;
bool operator>(const IPv6 & rhs) const;
bool operator==(const IPv6 & rhs) const;
bool operator<=(const IPv6 & rhs) const;
bool operator>=(const IPv6 & rhs) const;
bool operator!=(const IPv6 & rhs) const;
};
Import
#include <base/IPv4andIPv6.h>
Usage Examples
#include <base/IPv4andIPv6.h>
#include <unordered_map>
// Create IPv4 address (192.168.1.1)
IPv4 ipv4(0xC0A80101);
// Create IPv6 address
UInt128 addr_value = /* ... */;
IPv6 ipv6(addr_value);
// Type safety - won't compile
// IPv4 bad = ipv6; // Error: cannot convert IPv6 to IPv4
// Comparison
IPv6 addr1(value1);
IPv6 addr2(value2);
if (addr1 < addr2) {
// ...
}
// Use in hash tables
std::unordered_map<IPv4, std::string> ipv4_map;
ipv4_map[ipv4] = "localhost";
std::unordered_map<IPv6, std::string> ipv6_map;
ipv6_map[ipv6] = "::1";
// Access underlying value
UInt32 raw_ipv4 = ipv4.toUnderType();
UInt128 raw_ipv6 = ipv6.toUnderType();