accept函数的注意事项

一 accept函数原型

#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结构体大小的值,这样才能正常获取请求连接的信息.

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值