sockaddr_storage大小为128个字节

cst*_*fel 6 c c++ sockets

我只是想知道为什么sockaddr_storage是128字节.据我所知,它必须至少为IPv6的28个字节,但这似乎有点过于让100个额外字节大于sockaddr_in6.这仅仅是为了将来证明存储结构还是存在它现在需要的原因?

Mic*_*Mic 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).
Run Code Online (Sandbox Code Playgroud)