What is the usage of getsockopt in Linux?
`getsockopt()` in Linux is a system call function used to retrieve the value of socket options. Its prototype is as follows:
#include <sys/socket.h>int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen);
The meanings of the parameters are as follows:
sockfd:套接字文件描述符,指定要获取选项的套接字。level:选项所属的协议层级,常见的值有 SOL_SOCKET(通用套接字选项)和 IPPROTO_TCP(TCP协议选项)等。
optname:选项的名称,表示您要获取的具体选项。
optval:指向存储选项值的缓冲区的指针。
optlen:指向一个整数的指针,用于指定缓冲区的大小,并返回实际选项数据的长度。
The function `getsockopt()` retrieves the current value of the corresponding option by passing the `sockfd`, `level`, and `optname` parameters, and stores it in the buffer specified by `optval`. Upon successful call, it will return 0; otherwise, it returns -1 and sets the corresponding error code.
Here is a simple example of how to use it:
#include <stdio.h>#include <stdlib.h>
#include <sys/socket.h>
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket");
exit(1);
}
int option;
socklen_t option_len = sizeof(option);
// 获取套接字的 SO_REUSEADDR 选项值
if (getsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &option, &option_len) == -1) {
perror("getsockopt");
exit(1);
}
printf("SO_REUSEADDR: %d\n", option);
close(sockfd);
return 0;
}
The sample code here creates a socket and uses the `getsockopt()` function to obtain the current value of the `SO_REUSEADDR` option. The value is then printed out for your reference. Make adjustments based on your specific needs and option names.