问题
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:
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.
来源:https://stackoverflow.com/questions/2566915/setsockopt-sys-socket-h