gpt4 book ai didi

c - sockaddr 中 sa_data 字段的用途是什么?

转载 作者:太空狗 更新时间:2023-10-29 17:09:53 25 4
gpt4 key购买 nike

int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

为 addr 参数传递的实际结构将取决于地址族。 sockaddr 结构定义如下:

struct sockaddr {
sa_family_t sa_family;
char sa_data[14];
}

因此对于 IPv4 地址 (AF_INET),将传递的实际结构是这样的:

/* Source http://linux.die.net/man/7/ip */

struct sockaddr_in {
sa_family_t sin_family; /* address family: AF_INET */
in_port_t sin_port; /* port in network byte order */
struct in_addr sin_addr; /* internet address */
};

/* Internet address. */
struct in_addr {
uint32_t s_addr; /* address in network byte order */
};

绑定(bind)代码是否读取了 sockaddr.sa_family 值,并根据找到的值将 sockaddr 结构转换为适当的结构,例如 sockaddr_in?

为什么 sa_data 设置为 14 个字符?如果我理解正确,sa_data 字段只是一个具有足够大内存空间以适应所有地址族类型的字段?据推测,最初的设计者预计 14 个字符的宽度足以适应所有 future 的类型。

最佳答案

根据glibc manual :

The length 14 of sa_data is essentially arbitrary.

还有 FreeBSD developers handbook提到以下内容:

Please note the vagueness with which the sa_data field is declared, just as an array of 14 bytes, with the comment hinting there can be more than 14 of them.

This vagueness is quite deliberate. Sockets is a very powerful interface. While most people perhaps think of it as nothing more than the Internet interface—and most applications probably use it for that nowadays—sockets can be used for just about any kind of interprocess communications, of which the Internet (or, more precisely, IP) is only one.

是的,sa_family 字段用于识别如何处理传递的结构(在绑定(bind)调用中转换为 struct sockaddr*)。您也可以在 FreeBSD developers handbook 中阅读更多关于它如何工作的信息。 .

而且实际上还有sockaddr的“多态”(子)类型,其中sa_data包含超过16个字节,例如:

struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
char sun_path[108]; /* pathname */
};

关于c - sockaddr 中 sa_data 字段的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32624847/

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