setsockopt function
Namespace: Winsock2.h
Sets a socket option.
Syntax
#include <winsock2.h>
int setsockopt(
SOCKET s,
int level,
int optname,
const char *optval,
int optlen
);
#include <winsock2.h>
int setsockopt(
SOCKET s,
int level,
int optname,
const char *optval,
int optlen
);
Parameters
Parameter | Description |
---|---|
s | A descriptor identifying the socket. |
level | The level at which the option is defined (e.g., SOL_SOCKET ). |
optname | The name of the option to set (e.g., SO_REUSEADDR ). |
optval | Pointer to the buffer containing the new value for the option. |
optlen | Size of the buffer pointed to by optval , in bytes. |
Return Value
If the function succeeds, the return value is zero. On failure, SOCKET_ERROR
is returned, and a specific error code can be retrieved by calling WSAGetLastError
.
Remarks
The setsockopt
function can be used to configure various aspects of a socket such as timeouts, buffer sizes, and protocol-specific options. Some options are level‑specific (e.g., IPPROTO_TCP
for TCP options).
Note: Certain options require elevated privileges. Refer to the specific option documentation for details.
Example
/* Enable address reuse */
SOCKET listenSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int opt = 1;
int result = setsockopt(listenSock, SOL_SOCKET, SO_REUSEADDR,
(const char*)&opt, sizeof(opt));
if (result == SOCKET_ERROR) {
printf("setsockopt failed: %d\n", WSAGetLastError());
}