简体   繁体   中英

sockaddr_storage size of 128 bytes

I was just wondering why exactly the sockaddr_storage was 128 bytes. I understand it has to be at least what 28 bytes for IPv6 but this seems a little excessive to have like 100 extra bytes larger than sockaddr_in6. Is this just to future proof the storage struct or is there a reason that its needed right now?

You will find an answer to your questions in §3.10 of rfc 2553 and in this SO post .

The reason is a combination of should at least hold ip6 and other protocols data and 64-bit aligned for efficiency.

From the relevant part of the RFC:

One simple addition to the sockets API that can help application
writers is the "struct sockaddr_storage". This data structure can
simplify writing code portable across multiple address families and
platforms. This data structure is designed with the following goals.

  - 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. (eg 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). 

There might be systems which want to be able to fit a struct sockaddr_un in this structure as well. The latter has a system dependent path length of about 100 to 110 characters. And 128 is a beautifully even number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM