Linux下setsockopt函数相关用法(Usage of setsockopt function under Linux)

功能介绍

是用来为网络套接字设置选项值,比如:允许重用地址、网络超时等;在下和下均有该函数,但是使用略有不同;很多语言也支持或者封装了该接口

setsockopt
Linux
Windows

函数原型

#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>

int getsockopt(int sockfd, int level, int optname,
                      void *optval, socklen_t *optlen);
int setsockopt(int sockfd, int level, int optname,
                      const void *optval, socklen_t optlen);
  • sockfd:网络套接字
  • level:协议层,整个网络协议中存在很多层,指定由哪一层解析;通常是SOL_SOCKET,也有IPPROTO_IP/IPPROTO_TCP
  • optname:需要操作的选项,比如SO_RCVTIMEO接受超时
  • optval:设置的选项值,类型不定;比如SO_REUSERADDR设置地址重用,那么只需要传入一个int指针即可
  • optlen:选项值的长度

选项介绍

  • SO_REUSERADDR:允许本地地址和端口重用,参数为int类型;在Linux下主要作用是:关闭套接字监听后其地址很快能被另一个套接字使用;如果不设置的话,同一个程序绑定同一个端口,关闭后立马再次运行可能会遭遇绑定失败
  • “SO_RCVTIMEO:为接受数据的系统调用设置超时,包括:recv,recvfrom,accept;若超时, 返回-1,并设置errno`为EAGAIN或EWOULDBLOCK;网络套接字在运行中是会出现阻塞的情况,设置该值可能提升程序健壮性。

转载自https://www.jianshu.com/p/6e56735da7d7

————————

Function introduction

It is used to set option values for network sockets, such as allowing reuse of addresses, network timeout, etc; This function is used in both lower and lower, but the use is slightly different; Many languages also support or encapsulate this interface

setsockopt
Linux
Windows

Function prototype

#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>

int getsockopt(int sockfd, int level, int optname,
                      void *optval, socklen_t *optlen);
int setsockopt(int sockfd, int level, int optname,
                      const void *optval, socklen_t optlen);
  • Sockfd: network socket
  • Level: protocol layer. There are many layers in the whole network protocol. Specify which layer to resolve; Usually sol_ Socket and ipproto_ IP/IPPROTO_ TCP
  • optname:需要操作的选项,比如SO_RCVTIMEO接受超时
  • Optval: set the option value, with variable type; Such as so_ Reuseaddr sets address reuse, so you only need to pass in an int pointer
  • Optlen: length of option value

Option introduction

  • SO_ Reuseaddr: allows local address and port reuse. The parameter is int type; Under Linux, the main functions are: after closing socket listening, its address can be used by another socket soon; If it is not set, the same program binds to the same port, and running again immediately after closing may encounter binding failure
  • “SO_ Rcvtimeo: set timeout for system call receiving data, including: recv, recvfrom, accept; If timeout occurs, return – 1 and set errno ‘to eagain or ewouldblock; The network socket will be blocked during operation. Setting this value may improve the robustness of the program.

转载自https://www.jianshu.com/p/6e56735da7d7