we can see the api is defined as blow
int getsockopt(int sockfd, int level, int optname,
void *optval, socklen_t *optlen);
Question 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?
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
Have you looked at the Linux man page for getsockopt(2)
or the POSIX specification of getsockopt()
?
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.
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
.