clinuxgetsockopt

getsockopt api design questions


we can see the api is defined as blow

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

Question 1:

  1. Suppose given a level and optname, then we know the optlen, why do we need the user to provide the optlen parameter as well?

  2. even user provide the optlen, why it is a pointer to socklen_t rather than socklen_t directly? do the implementation will change the value of optlen somehow?

Thanks


Solution

  • Have you looked at the Linux man page for getsockopt(2) or the POSIX specification of getsockopt()?

    1. The optlen parameter is an in-out parameter. On input, it specifies how much space is available in the optval space, and on output, it reports how much of the space in optval was written to.

    2. Yes, the implementation changes the value of *optlen.

    For example, POSIX says:

    If the size of the option value is greater than option_len, the value stored in the object pointed to by the option_value argument shall be silently truncated. Otherwise, the object pointed to by the option_len argument shall be modified to indicate the actual length of the value.

    The specification uses option_len where you used optlen, and option_value where you used optval.