Search code examples
csetsockoptgetsockopt

Why must the fourth parameter of the setsockopt function and getsockopt function be a pointer?


When I was learning network programming, I noticed two functions, namely setsockopt() and getsockopt(). Among them, their fourth parameter is a pointer. However, in practical use, I feel that the fourth parameter almost always transfers numbers or Boolean values. So what is the meaning of using the fourth parameter as a pointer?

// Platform used for demonstration: Windows 10

// exmple 1
BOOL enable = TRUE;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&enable, sizeof(enable));

// or

// exmple 2
DWORD size = 2048;
setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&size, sizeof(size));

And I have checked the relevant documents, which do not mention the usage of this parameter as a buffer for strings or similar, so I am puzzled why this parameter must be a pointer.

Even when browsing through Python's documentation on the setsockopt function, I found that its fourth parameter accepts a string or byte string (Equivalent to a pointer).


Solution

  • Data of different types need to be exchanged.

    • A large number of options exchange an int.
    • SO_RCVTIMEO and SO_SNDTIMEO exchange a struct timeval.
    • SO_LINGER exchanges a struct linger.

    So a type compatible with each of these is required. A union could have been used, but that isn't forward-compatible. It would hinder the addition of new options. The remaining option is to use a void *.