文章目录
网络信息检索和套接字属性设置
网络信息检索函数 getsockopt
- get the socket options
#include <sys/socket.h>
int getsockopt(int socket, int level, int option_name, void *restrict option_value, socklen_t *restrict option_len);
The getsockopt()
function manipulates options associated with a socket.
The getsockopt()
function shall retrieve the value for the option specified by the option_name
argument for the socket specified by the socket
argument. If the size of the option value is greater than option_len
, the value stored in the object pointed to by the option_value
argument shall be silently truncated. Otherwise, the object pointed to by the option_len
argument shall be modified to indicate the actual length of the value.
The level
argument specifies the protocol level at which the option resides.
SOL_SOCKET
套接字层次IPPROTO_IP
IP 层次IPPROTO_TCP
tcp 层次
The option_name
argument specifies a single option to be retrieved. It can be one of the following values defined in <sys/socket.h>
:
SO_BROADCAST
- Reports whether transmission of broadcast messages is supported, if this is supported by the protocol. This option shall store an int value. This is a Boolean option.
SO_REUSEADDR
- Reports whether the rules used in validating addresses supplied to
bind()
should allow reuse of local addresses, if this is supported by the protocol. This option shall store an int value. This is a Boolean option.
SO_SNDBUF
- Reports send buffer size information. This option shall store an int value.
SO_RCVBUF
- Reports receive buffer size information. This option shall store an int value.
SO_RCVTIMEO
SO_SNDTIMEO
RETURN VALUE: Upon successful completion, getsockopt()
shall return 0
; otherwise, -1
shall be returned and errno
set to indicate the error.
获取缓存大小
int main()
{
char buf[N];
int nbyte;
int sockfd, acc_sockfd;
struct sockaddr_in server_addr, client_addr;
int client_addrlen = sizeof(client_addr); // 可以和 serverlen 公用?
// memset bzero
bzero(&server_addr, sizeof(server_addr));
bzero(&client_addr, client_addrlen);
// 填充服务器网络信息结构体
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr("192.168.1.163");
// 创建套接字
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
errlog("fail to socket");
// 将套接字与服务器网络信息结构体绑定
if(bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
errlog("fail to bind");
int opt_val;
socklen_t opt_len = sizeof(opt_val);
getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &opt_val, &opt_len);
printf("%dk\n", opt_val/1024);
getsockopt(sockfd