Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 which 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 *.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading