I want to know the proper way to determine which sockaddr variant to use.
From Beej's Guide to Network Programming:
if (p->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else { // IPv6
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
Here he is checking if the address family is AF_INET
and using sockaddr_in
if it is. If it isn't he is using sockaddr_in6
. Isn't that unsafe? What if it was some other address family that is not IPv6?
Is there a sanctioned, standard way of determining which structure maps to the corresponding address family?