指针在套接字编程中用于套接字地址的原因是什么?

huangapple go评论59阅读模式
英文:

Why pointer is used for socket address in socket programming?

问题

为什么在套接字地址中使用指针?

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
英文:

I have read many pages about socket programming and it's always says something like "Here we use the pointer to the address" and no explanation is given about why pointer is used for socket address.

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

Could someone please tell me why pointer is used for socket address?

答案1

得分: 3

man 2 accept明确说明了addraddrlen参数的用途:

参数addr是指向sockaddr结构的指针。该结构会填充为与通信层已知的对等端套接字的地址。返回的addr的确切格式取决于套接字的地址族(请参阅socket(2)和各自的协议手册)。当addr为NULL时,不会填充任何内容;在这种情况下,addrlen也不会被使用,应该为NULL。

addrlen参数是一个值-结果参数:调用者必须初始化它,以包含addr指向的结构的大小(以字节为单位);返回时,它将包含对等地址的实际大小。

总之,这些是您希望系统调用填充有关新建连接信息的对象的指针。

英文:

man 2 accept explicitly states the purpose of the addr and addrlen arguments within its first few paragraphs:

> The argument addr is a pointer to a sockaddr structure. This structure is filled in with the address of the peer socket, as known to the communications layer. The exact format of the address returned addr is determined by the socket's address family (see socket(2) and the respective protocol man pages). When addr is NULL, nothing is filled in; in this case, addrlen is not used, and should also be NULL.

> The addrlen argument is a value-result argument: the caller must initialize it to contain the size (in bytes) of the structure pointed to by addr; on return it will contain the actual size of the peer address.

In summary, these are pointers to objects you want the system call to fill with information about the newly formed connection.

huangapple
  • 本文由 发表于 2023年5月20日 21:32:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76295493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定