我目前正在编写一个使用网络结构(例如 sockaddr
)的 C 库。
在我的代码中,我使用这个三元条件来推断这种结构的大小。
addrlen = sourceaddr->sa_family ==
AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);
但是,大多数标准 UNIX 函数(例如 bind
)都具有这种签名:
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
它包含地址长度addrlen
的显式声明。
我的问题是:“如果我可以使用 sa_family
推导出地址 len,为什么我需要明确指示我的库中的地址 len?”
例如,绑定(bind)调用可以更改为以下签名:
int bind(int sockfd, const struct sockaddr *addr);
并在内部使用:
__bind(sockfd, addr,
addr->sa_family == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6));
非常感谢
最佳答案
它链接到不同操作系统之间的套接字 API 历史记录。每个系统都有自己的套接字实现,并且此类 API 之间没有标准化。
socklen_t is a strange typedef for the size of a struct sockaddr in accept(), getpeername(), and connect().
The reason for this typedef is that in BSD, those functions took an int*, and the POSIX people screwed it all up when they decided to make such arguments point to an integer of (potentially) another size, under a new typedef.
关于c - struct sockaddr,我们真的需要给addrlen吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41827400/