setsockopt
是 C++ 中用于设置套接字选项的函数
首先,需要包含相应的头文件:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
然后,创建一个套接字并连接到服务器:
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("connect");
exit(EXIT_FAILURE);
}
接下来,使用 setsockopt
设置套接字选项。以下是一些常见的选项:
int rcvbuf_size = 4096; // 4 KB
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf_size, sizeof(rcvbuf_size)) < 0) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
int sndbuf_size = 4096; // 4 KB
if (setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sndbuf_size, sizeof(sndbuf_size)) < 0) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
int keepalive_enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &keepalive_enable, sizeof(keepalive_enable)) < 0) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
int timeout_ms = 5000; // 5 seconds
if (setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &timeout_ms, sizeof(timeout_ms)) < 0) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
最后,关闭套接字:
close(sockfd);
请注意,这些示例中的选项仅供参考。您可以根据需要设置其他选项。在实际应用中,请确保正确处理错误并检查返回值。