面试题答案
一键面试以下是设置套接字接收缓冲区大小为8192字节的C语言代码片段:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUFFER_SIZE 8192
int main() {
int sockfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
int new_size = BUFFER_SIZE;
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &new_size, sizeof(new_size)) < 0) {
perror("Setsockopt failed");
close(sockfd);
exit(EXIT_FAILURE);
}
// 后续套接字相关操作
close(sockfd);
return 0;
}
涉及函数及参数含义
-
socket函数:
int socket(int domain, int type, int protocol);
domain
:指定协议族,如AF_INET
表示IPv4协议。type
:指定套接字类型,SOCK_STREAM
表示面向连接的字节流套接字(常用于TCP) 。protocol
:指定协议,一般为0,由domain
和type
决定使用的具体协议。
-
setsockopt函数:
int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen);
sockfd
:要设置选项的套接字描述符。level
:指定选项应用的协议层,SOL_SOCKET
表示应用于套接字通用选项。optname
:具体的选项名,这里SO_RCVBUF
表示设置接收缓冲区大小。optval
:指向存放选项值的缓冲区指针,这里是新的接收缓冲区大小new_size
。optlen
:optval
缓冲区的长度,这里是sizeof(new_size)
。