6

我只是想知道为什么 sockaddr_storage 是 128 字节。我知道 IPv6 必须至少有 28 个字节,但这似乎有点过分,比 sockaddr_in6 多出 100 个字节。这只是为了将来证明存储结构还是有理由现在需要它?

4

2 回答 2

6

您将在rfc 2553的 §3.10和此SO 帖子中找到您的问题的答案。

原因是应该至少保持 ip6 和其他协议数据64 位对齐以提高效率的组合。

从 RFC 的相关部分:


可以帮助应用程序编写者的套接字 API 的一个简单补充是“struct sockaddr_storage”。这种数据结构可以
简化编写跨多个地址族和
平台可移植的代码。该数据结构的设计目标如下。

  - It has a large enough implementation specific maximum size to
    store the desired set of protocol specific socket address data
    structures. Specifically, it is at least large enough to
    accommodate sockaddr_in and sockaddr_in6 and possibly other
    protocol specific socket addresses too.
  - It is aligned at an appropriate boundary so protocol specific
    socket address data structure pointers can be cast to it and
    access their fields without alignment problems. (e.g. pointers
    to sockaddr_in6 and/or sockaddr_in can be cast to it and access
    fields without alignment problems).
  - It has the initial field(s) isomorphic to the fields of the
    "struct sockaddr" data structure on that implementation which
    can be used as a discriminants for deriving the protocol in use.
    These initial field(s) would on most implementations either be a
    single field of type "sa_family_t" (isomorphic to sa_family
    field, 16 bits) or two fields of type uint8_t and sa_family_t
    respectively, (isomorphic to sa_len and sa_family_t, 8 bits
    each).
于 2013-02-25T20:27:24.780 回答
3

可能有些系统也希望能够适应struct sockaddr_un这种结构。后者具有大约 100 到 110 个字符的系统相关路径长度。128 是一个漂亮的偶数。

于 2013-02-25T20:26:22.207 回答