accept函数的注意事项

一 accept函数原型

1
2
3
4
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>

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

二 accept函数参数分析

  • sockfd参数是创建的socket的描述符,用来唯一表示一个socket.传入的socket必须是监听socket,这个参数较为简单,一般不会出错.

  • addr参数需注意是sockaddr结构体的指针,因历史原因,它仍然使用sockaddr结构体.现在较为常用的是sockaddr_in结构体,因为sockaddr_in能提供端口和ip的成员变量,在使用这个函数时应注意把sockaddr_in结构体的指针强制转换成sockaddr类型的指针.

  • addrlen参数较为容易出错,它是一个value-result参数,所以它不单单用来接收收到的addr结构体的大小,还要穿入一个值,在man手册中查到:

    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.

也就是说在调用函数之前,需要传入大于sockaddr结构体大小的值,这样才能正常获取请求连接的信息.