gpt4 book ai didi

c - 为什么从 sockaddr_in 到 sockaddr 的转换有效

转载 作者:IT王子 更新时间:2023-10-29 00:57:14 25 4
gpt4 key购买 nike

在 C 语言中,绑定(bind) Socket 的典型方式如下:

int server_socket_fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
int port_number = 55555;

addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port_number);

int result = bind(server_socket_fd,(struct sockaddr *)&addr , sizeof(addr));
if(bind_result > 0)
{
// Stuff
}

我想知道为什么从 sockaddr_insockaddr 的转换有效,因为我找不到任何说明它有效的文档。似乎每个人都这样做。

为什么类型转换在这里起作用?

我不是在问我们为什么投它,这已经被回答了here .我在问为什么它有效。

最佳答案

允许将结构指针转换为不同的结构指针并返回。这在 C standard 的第 6.3.2.3p7 节中有详细说明。 :

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer. When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.

上述段落中关于对齐的限制在 6.2.5p28 节中有进一步详细说明:

A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.48) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

据推测,bind 函数知道它拥有哪种套接字描述符并将 struct sockaddr * 转换回 struct sockaddr_in *

关于c - 为什么从 sockaddr_in 到 sockaddr 的转换有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51287930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com