Reputation: 572
I'm writing a client that can connect both to an IPv4 and an IPv6 address, making the code as generale as possible.
I used the getaddrinfo
function to which I pass the string of the IP address, and from that I obtain the address family (at this point I know if it's IPv4 or IPv6). Now I need to bind that address and the port to a sockaddr structure. I've read that in order to make it general I should use sockaddr_storage and then using it by casting it to sockaddr, but I don't understand how to fill sockaddr_storage with the address and the port needed for the connection.
Thanks for your attention.
NB. I want it to work on UNIX.
Upvotes: 1
Views: 139
Reputation: 409442
The POSIX specification only says that the sockaddr_storage
should be
Large enough to accommodate all supported protocol-specific address structures
Aligned at an appropriate boundary so that pointers to it can be cast as pointers to protocol-specific address structures and used to access the fields of those structures without alignment problems
And
The sockaddr_storage structure shall contain at least the following members:
sa_family_t ss_family
There's some notes saying that the family
structure member for all sockaddr
-family structures will be at the same place, but that's about it.
So the I would say that the "best" way to use it is to have special cases for IPv4 and IPv6 that fills in the correct sockaddr_in
or sockaddr_in6
structures, then memcpy
them into a sockaddr_storage
structure that can later be used.
Upvotes: 1