```html setsockopt function (winsock) – Windows API Reference | Microsoft Docs

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

ParameterDescription
sA descriptor identifying the socket.
levelThe level at which the option is defined (e.g., SOL_SOCKET).
optnameThe name of the option to set (e.g., SO_REUSEADDR).
optvalPointer to the buffer containing the new value for the option.
optlenSize 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());
}

See Also

```