简体   繁体   English

从 sockaddr_in* 到 sockaddr* 的类型转换是否违反了“严格的别名规则”?

[英]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"?以下类型从sockaddr_in * 转换为sockaddr * 是否违反“严格别名规则”?

Example code snippet from "Beej's Guide to Network programming" (version 2.3.23).来自“Beej 网络编程指南”(版本 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.许多 UNIX 网络基础都是建立在这些创造性的“滥用”结构之上的。 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.这会使在非 C 代码中使用这些函数和结构变得相当困难,因为许多语言(如 C++)默认禁止此类任意重铸操作。

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.在 C++ 中,您需要处理这样一个事实,是的,从技术上讲,这些都不是有效的转换,但 UNIX 网络规范已经存在了几十年并且是一种众所周知的商品。 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.与往常一样,您需要小心行事,尤其是在进行此类演员时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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