4
votes

I am reading Beej's guide, and he talks about the different structers programmers created. He says we can pass sockaddr_storage/in6/in to addrinfo, and it will be converted to sockaddr, but how exactly is it possible? sockaddr is 16 bytes, while sockaddr_in6 is 28 bytes.

I read a little part of RFC 3493:

Notice that the sockaddr_in6 structure will normally be larger than
the generic sockaddr structure. On many existing implementations the sizeof(struct sockaddr_in) equals sizeof(struct sockaddr), with both
being 16 bytes. Any existing code that makes this assumption needs
to be examined carefully when converting to IPv6.

But it doesn't explain what happens when sockaddr_in6 is casted to sockaddr.

1

1 Answers

6
votes

Remember that all functions that take a struct sockaddr pointer, also takes the size of the structure. Together with the meta-data on the actual socket, it's easy for the system to know what kind of structure you're passing.

Also note that it's always pointers to the address structures being passed around, not actual structures which would not work. So you never to e.g.

(struct sockaddr) a_in6_sockaddr

you do

(struct sockaddr *) &a_in6_sockaddr