为什么在socket编程中accept()中使用socklent_t *? [英] Why socklent_t * is used in accept() in socket programming?
问题描述
在 C 套接字编程中,accept()
声明如下所示:
In C socket programming the accept()
declaration looks like:
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
我能理解sockfd
、struct sockaddr *addr
的用法.
但是为什么我们必须传递套接字长度的地址,它可能是socklen_t
.因为如果accept()
函数需要长度,那么它可以通过socklen_t
来获取.为什么函数的原型是这样声明的?
But why we have to pass the address of the length of the socket, it could have been socklen_t
. Because if the accept()
function needs the length then it can get it by socklen_t
. Why the protype of the function is declared in such that way?
那么使用 socklen_t *
类型的原因是什么?
So what is the reason behind using socklen_t *
type?
推荐答案
在与其接受的套接字的地址/协议族无关的代码中,它可能使用通用的 sockaddr_storage
结构来保持结果.指向的socklen_t
的初始值就是这个存储的大小;accept
返回后的值是结果对等地址的实际大小.此外,一些地址/协议族(如 AF_UNIX
)具有可变长度的地址,因此即使您知道类型,您也可能不知道大小.
In code that's agnostic to the address/protocol family of the socket it's accepting from, it may be using a generic sockaddr_storage
structure to hold the result. The initial value of the pointed-to socklen_t
is the size of this storage; the value after accept
returns is the actual size of the resulting peer address. Also, some address/protocol families like AF_UNIX
have variable length addresses, so even if you know the type you may not know the size.
这篇关于为什么在socket编程中accept()中使用socklent_t *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!