遵循我以前的question,我对这个代码真的很好奇-
case AF_INET:
{
struct sockaddr_in * tmp =
reinterpret_cast<struct sockaddr_in *> (&addrStruct);
tmp->sin_family = AF_INET;
tmp->sin_port = htons(port);
inet_pton(AF_INET, addr, tmp->sin_addr);
}
break;
在问这个问题之前,我在SO上搜索了相同的主题,并得到了关于该主题的混合答案。例如,请参见this,this和this帖子,其中指出使用这种代码在某种程度上是安全的。另外还有另一个post,它说使用 union 执行此任务,但是对接受的答案的评论也再次有所不同。
微软在相同结构上的documentation说-
Application developers normally use only the ss_family member of the SOCKADDR_STORAGE. The remaining members ensure that the SOCKADDR_STORAGE can contain either an IPv6 or IPv4 address and the structure is padded appropriately to achieve 64-bit alignment. Such alignment enables protocol-specific socket address data structures to access fields within a SOCKADDR_STORAGE structure without alignment problems. With its padding, the SOCKADDR_STORAGE structure is 128 bytes in length.
Opengroup的documentation状态-
The header shall define the sockaddr_storage structure. This structure shall be:
Large enough to accommodate all supported protocol-specific address structures
Aligned at an appropriate boundary so that pointers to it can be cast as pointers to protocol-specific address structures and used to access the fields of those structures without alignment problems
socket的手册页也说相同-
In addition, the sockets API provides the data type struct sockaddr_storage. This type is suitable to accommodate all supported domain-specific socket address structures; it is large enough and is aligned properly. (In particular, it is large enough to hold IPv6 socket addresses.)
我已经在野外看到了在
C
和C++
语言中使用此类强制转换的多种实现方式,现在我不确定哪个是对的,因为有些帖子与上述主张相抵触-this和this。那么,哪种方法是填充
sockaddr_storage
结构的安全正确的方法?这些指针强制转换安全吗?还是union method?我也知道getaddrinfo()
调用,但是对于上述仅填充结构的任务来说似乎有点复杂。还有另一个recommended way with memcpy,这样安全吗?
最佳答案
与设计sockaddr
接口(interface)甚至编写C99时相比,过去十年中C和C++编译器变得更加复杂。作为其一部分,已理解的“未定义行为”的目的已经改变。回顾过去,未定义的行为通常旨在涵盖硬件实现之间关于操作语义是什么的分歧。但是如今,最终归功于许多组织希望停止编写FORTRAN并有能力支付编译器工程师来实现这一目标,未定义的行为是编译器用来推断代码的事情。左移是一个很好的例子:C99 6.5.7p3,4(为清晰起见,重新排列了一下)读取
The result of
E1 << E2
isE1
left-shiftedE2
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.
因此,例如,在
1u << 33
为32位宽的平台上,unsigned int
是UB。该委员会之所以没有定义此定义,是因为在这种情况下,不同的CPU架构的左移指令执行不同的操作:有些始终产生零,有些减少了类型宽度(x86)的模数,有些减少了模数的模数。 (ARM),并且至少会有一种历史上常见的体系结构会陷入陷阱(我不知道是哪一种,但这就是为什么它是未定义且未指定的原因)。但是现在,如果你写unsigned int left_shift(unsigned int x, unsigned int y)
{ return x << y; }
在具有32位
unsigned int
的平台上,编译器了解上述UB规则,将在调用该函数时推断y
必须具有介于0到32之间的值。它将把该范围输入到过程间分析中,并使用它来执行诸如在调用方中删除不必要的范围检查之类的操作。如果程序员有理由认为它们不是不必要的,那么,现在您开始了解为什么这个主题如此蠕虫。有关针对未定义行为的目的进行的更改的更多信息,请参阅LLVM人们关于该主题的三部分文章(1 2 3)。
现在您已经了解了,我实际上可以回答您的问题。
在消除了一些不相关的并发症之后,这些是
struct sockaddr
,struct sockaddr_in
和struct sockaddr_storage
的定义: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;
};
这是穷人的子类化。它是C语言中的一个普遍用法。您定义了一组结构,所有结构都具有相同的初始字段,这是一个代码号,用于告诉您实际上已传递了哪种结构。早在今天,每个人都希望如果您分配并填写了
struct sockaddr_in
,将其上传到struct sockaddr
,然后将其传递给例如connect
,connect
的实现可以安全地取消引用struct sockaddr
指针以检索sa_family
字段,了解它正在查看sockaddr_in
,将其抛回然后继续。 C标准始终表示,取消引用struct sockaddr
指针会触发未定义的行为-自C89以来,这些规则未更改-但每个人都希望在这种情况下它是安全的,因为无论您使用哪种结构,它都是相同的“加载16位”指令真的在合作。这就是POSIX和Windows文档谈论对齐的原因。早在1990年代编写这些规范的人就认为,实际上可能造成麻烦的主要方式是,如果您结束发布未对齐的内存访问。但是该标准的文本中没有任何关于加载指令或对齐的内容。它是这样说的(C99§6.5p7+脚注):
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
类型仅与它们自己“兼容”,并且声明的变量的“有效类型”是其声明的类型。所以您显示的代码...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;
...具有未定义的行为,即使幼稚的代码生成将按预期运行,编译器也可以从中进行推断。现代编译器可能会由此推断出,
case AF_INET
永远无法执行。它将整个块删除为死代码,并随之而来。那么,如何安全地使用
sockaddr
?最简单的答案是“只使用 getaddrinfo
和 getnameinfo
”。他们为您解决了这个问题。但是也许您需要使用
AF_UNIX
无法处理的地址族,例如getaddrinfo
。在大多数情况下,您只需要为地址族声明一个正确类型的变量,并仅在调用带有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;
}
connect
的实现必须跳过一些箍以确保此安全,但这不是您的问题。与另一个答案相反,在一种情况下,您可能想使用
sockaddr_storage
;在需要同时处理IPv4和IPv6地址的服务器中,与getpeername
和getnameinfo
结合使用。这是一种方便的方法,可以知道要分配多少缓冲区。#ifndef NI_IDN
#define NI_IDN 0
#endif
char *get_peer_hostname(int sock)
{
char addrbuf[sizeof(struct sockaddr_storage)];
socklen_t addrlen = sizeof addrbuf;
if (getpeername(sock, (struct sockaddr *)addrbuf, &addrlen))
return 0;
char *peer_hostname = malloc(MAX_HOSTNAME_LEN+1);
if (!peer_hostname) return 0;
if (getnameinfo((struct sockaddr *)addrbuf, addrlen,
peer_hostname, MAX_HOSTNAME_LEN+1,
0, 0, NI_IDN) {
free(peer_hostname);
return 0;
}
return peer_hostname;
}
(我也可以写
struct sockaddr_storage addrbuf
,但是我想强调一点,我实际上并不需要直接访问addrbuf
的内容。)最后要注意的是:如果BSD人员已经对sockaddr结构进行了定义,则稍有不同...
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;
};
...由于“包含上述类型之一的聚合或 union ”规则,上流和下流本来可以很好地定义。
如果您想知道如何在新的C代码中处理此问题,请继续。
关于c++ - 将围绕sockaddr_storage和sockaddr_in进行转换将破坏严格的别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42178179/