C and C++ compilers have become much more sophisticated in the past decade than they were when the sockaddr
interfaces were designed, or even when C99 was written. As part of that, the understood purpose of "undefined behavior" has changed. Back in the day, undefined behavior was usually intended to cover disagreement among hardware implementations as to what the semantics of an operation was. But nowadays, thanks ultimately to a number of organizations who wanted to stop having to write FORTRAN and could afford to pay compiler engineers to make that happen, undefined behavior is a thing that compilers use to make inferences about the code. Left shift is a good example: C99 6.5.7p3,4 (rearranged a little for clarity) reads
The result of E1 << E2
is E1
left-shifted E2
bit positions; vacated bits are filled with zeros. If the value of [E2
] is negative or is
greater than or equal to the width of the promoted [E1
], the behavior is undefined.
So, for instance, 1u << 33
is UB on a platform where unsigned int
is 32 bits wide. The committee made this undefined because different CPU architectures' left-shift instructions do different things in this case: some produce zero consistently, some reduce the shift count modulo the width of the type (x86), some reduce the shift count modulo some larger number (ARM), and at least one historically-common architecture would trap (I don't know which one, but that's why it's undefined and not unspecified). But nowadays, if you write
unsigned int left_shift(unsigned int x, unsigned int y)
{ return x << y; }
on a platform with 32-bit unsigned int
, the compiler, knowing the above UB rule, will infer that y
must have a value in the range 0 through 31 when the function is called. It will feed that range into interprocedural analysis, and use it to do things like remove unnecessary range checks in the callers. If the programmer has reason to think they aren't unnecessary, well, now you begin to see why this topic is such a can of worms. (Modern compilers can optimize x << (y&31)
into a single shift instruction for ISAs like x86 where the shift instruction implements that masking.)
For more on this change in the purpose of undefined behavior, please see the LLVM people's three-part essay on the subject (1 2 3).
Now that you understand that, I can actually answer your question.
These are the definitions of struct sockaddr
, struct sockaddr_in
, and struct sockaddr_storage
, after eliding some irrelevant complications:
struct sockaddr {
uint16_t sa_family;
};
struct sockaddr_in {
uint16_t sin_family;
uint16_t sin_port;
uint32_t sin_addr;
};
struct sockaddr_storage {
uint16_t ss_family;
char __ss_storage[128 - (sizeof(uint16_t) + sizeof(unsigned long))];
unsigned long int __ss_force_alignment;
};
This is poor man's subclassing. It is a ubiquitous idiom in C. You define a set of structures that all have the same initial field, which is a code number that tells you which structure you've actually been passed. Back in the day, everyone expected that if you allocated and filled in a struct sockaddr_in
, upcast it to struct sockaddr
, and passed it to e.g. connect
, the implementation of connect
could dereference the struct sockaddr
pointer safely to retrieve the sa_family
field, learn that it was looking at a sockaddr_in
, cast it back, and proceed. The C standard has always said that dereferencing the struct sockaddr
pointer triggers undefined behavior—those rules are unchanged since C89—but everyone expected that it would be safe in this case because it would be the same "load 16 bits" instruction no matter which structure you were really working with. That's why POSIX and the Windows documentation talk about alignment; the people who wrote those specs, back in the 1990s, thought that the primary way this could actually be trouble was if you wound up issuing a misaligned memory access.
But the text of the standard doesn't say anything about load instructions, nor alignment. This is what it says (C99 §6.5p7 + footnote):
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:73)
- a type compatible with the effective type of the object,
- a qualified version of a type compatible with the effective type of the object,
- a type that is the signed or unsigned type corresponding to the effective type of the
object,
- a type that is the signed or unsigned type corresponding to a qualified version of the
effective type of the object,
- an aggregate or union type that includes one of the aforementioned types among its
members (including, recursively, a member of a subaggregate or contained union), or
- a character type.
73) The intent of this list is to specify those circumstances in which an object may or may not be aliased.
struct
types are "compatible" only with themselves, and the "effective type" of a declared variable is its declared type. So the code you showed...
struct sockaddr_storage addrStruct;
/* ... */
case AF_INET:
{
struct sockaddr_in * tmp = (struct sockaddr_in *)&addrStruct;
tmp->sin_family = AF_INET;
tmp->sin_port = htons(port);
inet_pton(AF_INET, addr, tmp->sin_addr);
}
break;
... has undefined behavior, and compilers can make inferences from that, even though naive code generation would behave as expected. What a modern compiler is likely to infer from this is that the case AF_INET
can never be executed. It will delete the entire block as dead code, and hilarity will ensue.
So how do you work with sockaddr
safely? The shortest answer is "just use getaddrinfo
and getnameinfo
." They deal with this problem for you.
But maybe you need to work with an address family, such as AF_UNIX
, that getaddrinfo
doesn't handle. In most cases you can just declare a variable of the correct type for the address family, and cast it only when calling functions that take a struct sockaddr *
int connect_to_unix_socket(const char *path, int type)
{
struct sockaddr_un sun;
size_t plen = strlen(path);
if (plen >= sizeof(sun.sun_path)) {
errno = ENAMETOOLONG;
return -1;
}
sun.sun_family = AF_UNIX;
memcpy(sun.sun_path, path, plen+1);
int sock = socket(AF_UNIX, type, 0);
if (sock == -1) return -1;
if (connect(sock, (struct sockaddr *)&sun,
offsetof(struct sockaddr_un, sun_path) + plen)) {
int save_errno = errno;
close(sock);
errno = save_errno;
return -1;
}
return sock;
}
The implementation of connect
has to jump through some hoops to make this safe, but that is Not Your Problem.
[EDIT Jan 2023: What this answer used to say about sockaddr_storage
was wrong and I'm embarrassed to admit I didn't notice the problem for six years.] It is tempting to use struct sockaddr_storage
as a convenient way to know how big to make the buffer for a call to getpeername
, in a server that needs to handle both IPv4 and IPv6 addresses. However, it is less error-prone and has fewer strict-aliasing problems if you use a union
with each of the concrete address families you care about, plus plain struct sockaddr
:
#ifndef NI_IDN
#define NI_IDN 0
#endif
union sockaddr_ipvX {
struct sockaddr sa;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
};
char *get_peer_hostname(int sock)
{
union sockaddr_ipvX addrbuf;
socklen_t addrlen = sizeof addrbuf;
if (getpeername(sock, &addrbuf.sa, &addrlen))
return 0;
char *peer_hostname = malloc(MAX_HOSTNAME_LEN+1);
if (!peer_hostname) return 0;
if (getnameinfo(&addrbuf.sa, addrlen,
peer_hostname, MAX_HOSTNAME_LEN+1,
0, 0, NI_IDN) {
free(peer_hostname);
return 0;
}
return peer_hostname;
}
With this formulation, not only do you not need to write any casts to call getpeername
or getnameinfo
, you can safely access addrbuf.sa.sa_family
and then, when sa_family == AF_INET
, addrbuf.sin.sin_*
.
A final note: if the BSD folks had defined the sockaddr structures just a little bit differently ...
struct sockaddr {
uint16_t sa_family;
};
struct sockaddr_in {
struct sockaddr sin_base;
uint16_t sin_port;
uint32_t sin_addr;
};
struct sockaddr_storage {
struct sockaddr ss_base;
char __ss_storage[128 - (sizeof(uint16_t) + sizeof(unsigned long))];
unsigned long int __ss_force_alignment;
};
... upcasts and downcasts would have been perfectly well-defined, thanks to the "aggregate or union that includes one of the aforementioned types" rule.
If you're wondering how you should deal with this problem in new C code, here you go.
reinterpret_cast
if you are not sure and in particular you should never do it on structures you have not defined (except if it clearly documented as valid). – Gluttonize