There has been already much said in the mentioned SO thread. But I would not care too much. Here is my (a bit pragmatic) view:
These socket structures are a little bit special because the
sockaddr
parameter of the socket functions is usually never passed as such but by casting an appropriate type like
sockaddr_in
or
sockaddr_in6
. The first member of the structures (the family) defines how the passed data will be interpreted (and therefore also the max. size of the passed struct).
So casting here is by intention (don't forget that the socket functions are from the C standard library).
It is common to declare a variable of the required type and pass that casting it to
sockaddr
. So there is no need to create a larger struct when you only want to pass an IPv4 struct for example. If you would have to decide the data type during program execution you can use a larger struct like
sockaddr_storage
and cast that like you have done or use two code blocks with the matching structs and call the socket function within the block.
In any case there should be no need to copy the data.
BTW: There is no need to cast here:
memcpy(reinterpret_cast<char *>(&addrStruct),
reinterpret_cast<char *>(&sin), sizeof(sin));
The
memcpy
parameters are
void*
and not
char*
.