gpt4 book ai didi

postgresql - 由于 IPV6 需要 128 位(16 字节)那么为什么在 postgres CIDR 数据类型中存储为 24 字节(8.1)和 19 字节(9.1)?

转载 作者:行者123 更新时间:2023-11-29 11:23:51 41 4
gpt4 key购买 nike

我正在使用 ipv4 和 ipv6 存储在 postgres 数据库中。

因为 ipv4 需要 32 位(4 字节)而 ipv6 需要 128(16 字节)位。那么为什么在 postgres 中 CIDR 和 INET 数据类型对于 IPV4 和 IPV6(8.1)分别具有 12 字节和 24 字节的存储。

在9.1中,IPV4和IPV6分别有7字节和19字节。

我不明白为什么它需要额外的字节超过 16 字节来存储 IPV6 和 4 字节来存储 IPV4??

http://www.postgresql.org/docs/8.1/static/datatype-net-types.html

http://www.postgresql.org/docs/9.1/interactive/datatype-net-types.html

最佳答案

sourcecode IP 数据类型显示如下:

typedef struct
{
unsigned char family; /* PGSQL_AF_INET or PGSQL_AF_INET6 */
unsigned char bits; /* number of bits in netmask */
unsigned char ipaddr[16]; /* up to 128 bits of address */
} inet_struct;

这意味着,除了 ipaddr 中的“原始”数据(IP4 为 4 个字节,IP6 为 16 个字节)之外,还有一个字节用于网络掩码和一个字节用于地址族(基本上是 IP4/IP6 的开关)。

此外还有 varlena 开销,在同一个文件中提到:

/*
* Both INET and CIDR addresses are represented within Postgres as varlena
* objects, ie, there is a varlena header in front of the struct type
* depicted above. This struct depicts what we actually have in memory
* in "uncompressed" cases. Note that since the maximum data size is only
* 18 bytes, INET/CIDR will invariably be stored into tuples using the
* 1-byte-header varlena format. However, we have to be prepared to cope
* with the 4-byte-header format too, because various code may helpfully
* try to "decompress" 1-byte-header datums.
*/
typedef struct
{
char vl_len_[4]; /* Do not touch this field directly! */
inet_struct inet_data;
} inet;

所以 IP4 的等式是这样的:

1 byte varlena
1 byte address family
1 byte netmask
4 raw bytes
===========
7 byte total

对于 IP6,相同的公式为您提供 19 个字节。

编辑 旧版本的 PostgreSQL 只有 4 字节的 varlena 表示。因此,您可以为每种类型添加 3 个字节(IP4:10,IP6:22)。最重要的是有一个填充到下一个 4 字节边界。这为每种类型提供了 2 个字节,总计 12 或 24 个字节。

This mail阐明了较短版本的开发。

关于postgresql - 由于 IPV6 需要 128 位(16 字节)那么为什么在 postgres CIDR 数据类型中存储为 24 字节(8.1)和 19 字节(9.1)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11542680/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com