getsockopt()函數用于獲取套接字選項的當前值。
int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen);
參數說明:
返回值:
常見的level和optname參數:
示例代碼:
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket");
return 1;
}
int sndbuf;
socklen_t len = sizeof(sndbuf);
int ret = getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sndbuf, &len);
if (ret == 0) {
printf("SO_SNDBUF: %d\n", sndbuf);
} else {
perror("getsockopt");
}
int nodelay;
len = sizeof(nodelay);
ret = getsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &nodelay, &len);
if (ret == 0) {
printf("TCP_NODELAY: %d\n", nodelay);
} else {
perror("getsockopt");
}
close(sockfd);
return 0;
}
上述代碼獲取了套接字的發送緩沖區大小和禁用Nagle算法的狀態。