简体   繁体   中英

Is the type cast from sockaddr_in* to sockaddr* a violation of "strict aliasing rule"?

Is the following type cast from sockaddr_in * to sockaddr * a violation of "strict aliasing rule"?

Example code snippet from "Beej's Guide to Network programming" (version 2.3.23). The typecast is happening at the last line.

...
#include <arpa/inet.h>
#define MYPORT 3490
main()
{
int sockfd;
struct sockaddr_in my_addr;
sockfd = socket(PF_INET, SOCK_STREAM, 0); 
my_addr.sin_family = AF_INET; 
my_addr.sin_port = htons(MYPORT); 
my_addr.sin_addr.s_addr = inet_addr("10.12.110.57");
memset(&(my_addr.sin_zero), ’\0’, 8); 
bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));

Here, for convenience, I'm including those struct definitions:

struct sockaddr {
    unsigned short    sa_family;    // address family, AF_xxx
    char              sa_data[14];  // 14 bytes of protocol address
};


// IPv4 AF_INET sockets:

struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

struct in_addr {
    unsigned long s_addr;          // load with inet_pton()
};

A lot of the UNIX networking foundations are built on these sorts of creative "abuses" of structures. This can make using these functions and structures in non C code quite difficult as many languages, like C++, forbid these sorts of arbitrary recasting operations by default.

In C++ you will need to deal with the fact that, yes, technically these are not valid casts, but the UNIX networking specification has been around for decades and is a known commodity. You can make reasonable assumptions about what is and isn't a valid conversion regardless of what the compiler insists.

As always you will need to tread carefully, but especially when doing these sorts of casts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM