setsockopt (sys/socket.h)

lojin picture lojin · Apr 2, 2010 · Viewed 7.5k times · Source

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

Answer

mark4o picture mark4o · Apr 2, 2010

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.