sockaddr_storage大小为128个字节

时间:2013-02-25 20:20:25

标签: c++ c sockets

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

2 个答案:

答案 0 :(得分:5)

您可以在rfc 2553的§3.10和此SO post中找到问题的答案。

原因是的组合应该至少保持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).

答案 1 :(得分:2)

可能还有一些系统希望能够在此结构中容纳struct sockaddr_un。后者具有大约100到110个字符的系统相关路径长度。 128是一个非常均匀的数字。