TL; DR: This warning does not indicate an error in your code, but you can avoid this by using poper C ++ reinterpret_cast (thanks to @Kurt Stutsman).
Explanation:
Reason for warning :
sockaddr consists of an array of unsigned short (usually 16 bits) and char, so its alignment requirement is 2.sockaddr_in contains (among other things) a struct in_addr , which has an alignment requirement of 4, which in turn means sockaddr_in , must also be aligned with a 4 byte boundary.
For this reason, casting arbitrary sockaddr* to sockaddr_in* changes the alignment requirement, and accessing the object using the new pointer will even violate alias rules and lead to undefined behavior.
Why you can ignore it :
In your case, the object p->ai_addr indicates, most likely, it is the sockaddr_in or sockaddr_in6 object in any case (as determined by checking ai_family ), and therefore the operation is safe. However, the compiler does not know this and issues a warning.
In essence, this is the same as using static_cast to point to a pointer to a base class and a pointer to a derived class - it is unsafe in the general case, but if you know the correct dynamic type in appearance, it is well defined.
Decision:
I do not know how to do this (other than a warning), which is unusual for warnings allowed by -Weverything . You can copy the byte by tte object by byte to an object of the corresponding type, but then you will most likely not use addr same way as before, since it will now point to another (for example, local).
-Weverything is not what I would use for my usual builds anyway, because it adds too much noise, but if you want to keep it, @Kurt Stutsman mentioned a good solution in the comments:
clang ++ (g ++ does not give a warning in any case) does not give a warning if you use reinterpret_cast instead of c style styles (which you should not use in any case), although both have (in this case) exactly the same functionality. Perhaps because reinterpret_cast explicitly tells the compiler: "Believe me, I know what I'm doing."
On the side Note: in C ++ code you do not need the struct keywords.
source share