sockaddr_storage大小为128字节

sockaddr_storage size of 128 bytes

本文关键字:小为 128字节 storage sockaddr      更新时间:2023-10-16

我只是想知道为什么sockaddr_storage是128字节。我知道IPv6至少需要28个字节,但比sockaddr_in6多出100个字节似乎有点过分。这只是为了让存储结构经得起未来考验,还是有理由现在就需要它?

您将在rfc 2553的§3.10和本SO文章中找到问题的答案。

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

来自RFC的相关部分:

插座API的一个简单添加,可以帮助应用程序
writers是"structsockaddr_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).

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