Detailed explanation of the getsockopt( ) function

The getsockopt() function is used to retrieve the current value of a socket option.

int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen);

Description of parameters:

  1. sockfd: socket file descriptor.
  2. Level: The protocol layer where the option is located.
  3. option name: name of the option
  4. optval: output parameter, used to store the value of the option.
  5. optlen: Input/output parameter that specifies the size of the optval buffer and returns the actual length of the obtained option value.

Return value:

  1. Success: 0
  2. Failure: -1, and set errno.

Common parameters for level and optname:

  1. Options for level SOL_SOCKET:

    – SO_SNDBUF: Size of the send buffer.
    – SO_RCVBUF: Size of the receive buffer.
    – SO_REUSEADDR: Allowing address reuse.

  2. Options with level IPPROTO_TCP:

    TCP_KEEPIDLE: Timeout time when TCP connection is idle.
    TCP_KEEPINTVL: Time interval for TCP keep-alive probes.
    TCP_NODELAY: Disable Nagle’s algorithm.

Example code:

#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;
}

The above code retrieves the size of the socket’s sending buffer and the status of disabling the Nagle algorithm.

广告
Closing in 10 seconds
bannerAds