views:

309

answers:

2

The prototype for setsockopt is:

int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len);

Are the following all correct ? Which are not ?

a.) int buffsize = 50000; setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&buffsize, sizeof(buffsize));

b.) int buffsize = 50000; setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void *)&buffsize, sizeof(buffsize));

c.) char *buffsize = "50000"; setsockopt(s, SOL_SOCKET, SO_RCVBUF, buffsize, strlen(buffsize));

d.) setsockopt(s, SOL_SOCKET, SO_RCVBUF, "50000", 5);

+1  A: 

The SO_RCVBUF option is defined as having a parameter type of int, so (c) and (d) are not correct.

http://www.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tagtcjh_8

Because C will automatically convert an int * to const void *, no cast is required:

int buffsize = 50000;
setsockopt(s, SOL_SOCKET, SO_RCVBUF, &buffsize, sizeof(buffsize));

However, because char * and void * will also be automatically converted, (a) and (b) should also work.

mark4o
A: 
lojin
(1) is wrong because the `option_value` argument is a *pointer* to the parameter value. (2) is ok if you add `timeout.tv_usec = 0;`.
mark4o