Wienke
Wienke

Reputation: 3733

What is the purpose of setsockopt's option_len arg?

Example:

// socket created above this
int iSocketOption = 1; 
setsockopt(CFSocketGetNative(socket), SOL_SOCKET, SO_REUSEADDR, (void *)&iSocketOption, sizeof(iSocketOption));

I understand that when you pass a wildcard pointer to the address of an int set to 1 for the option_value arg (4th arg), you are saying, yes, use the SO_REUSEADDR option.

But what is going on with option_len, the last arg? The idea seems to be to recycle the int used for the arg before it, making it into a buffer for reporting the size of an unrelated value. What is that unrelated value? Should I be doing something with it?

Here’s the excerpt from the BSD Systems Calls Manual that’s confusing me:

For getsockopt(), option_len is a value-result parameter, initially containing the size of the buffer pointed to by option_value, and modified on return to indicate the actual size of the value returned.

What is the value whose size is to be returned using the buffer passed in via the penultimate arg of setsockopt?

(Granted, the excerpt regards getsockopt, not setsockopt, but there’s no other explanation of that last arg.)


Why I asked this question:

Apress’s More iPhone 3 Development gives this example of a socket setup, inside a method that returns a BOOL:

- (BOOL) methodInvolvingSocket {
// socket creation
int ret = 1; 
setsockopt(CFSocketGetNative(socket), SOL_SOCKET, SO_REUSEADDR, (void *)&ret,
sizeof(ret));
//...socket address set up, but no further use of “ret.”
return ret;
}

At the end of this method, the return is made using “ret” — which works, because ret is 1, the equivalent of YES, but it’s a pretty weird thing to do unless there were some expectation that the value of “ret” might change.

Upvotes: 0

Views: 1555

Answers (2)

Moshe Katz
Moshe Katz

Reputation: 16883

Your guess from the other answer's comments is correct.

setsockopt works for setting many different types of values. While many (possibly even most) are of type int, others are structs of varying sizes. Since the only thing that setsockopt gets is a pointer, it has no way of knowing how large the struct is and that's why you need to tell it.

For some examples of other types of values, see the GNU C documentation at http://www.delorie.com/gnu/docs/glibc/libc_352.html

The same is true for getsockopt, only the other way around. It assumes that you don't know how big the type is so it puts the size into the int that you provide for it. You need to set its value to the size of the buffer in order to prevent a buffer overflow when you get the value.

Upvotes: 3

For setsockopt the last parameter does nothing more than tell the function how long the memory pointer to by the parameter before that is.

Upvotes: 2

Related Questions