getsockopt
Header: winsock2.h
Library: Ws2_32.lib
Synopsis
int getsockopt(
SOCKET s,
int level,
int optname,
char *optval,
int *optlen
);
Parameters
Parameter | Description |
---|---|
s | The descriptor identifying the socket. |
level | Protocol level at which the option resides. Typical values: SOL_SOCKET , IPPROTO_TCP , IPPROTO_IP . |
optname | Option name to query. Examples: SO_RCVBUF , SO_ERROR , TCP_NODELAY . |
optval | Pointer to a buffer that receives the option value. |
optlen | On input, size of optval . On output, number of bytes actually written. |
Return Value
Returns 0
on success. On failure, returns SOCKET_ERROR
and the error code can be retrieved with WSAGetLastError
.
Remarks
- The
optval
buffer must be large enough for the requested option. - Commonly used to retrieve the current state of socket options such as
SO_RCVBUF
(receive buffer size) orSO_ERROR
(pending error). - For IPv6 options, use
IPPROTO_IPV6
as the level. - When querying
SO_ERROR
, the value is cleared after the call.
Example
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
int main() {
WSADATA wsaData;
SOCKET s;
int recvBufSize = 0;
int optLen = sizeof(recvBufSize);
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
printf("WSAStartup failed\\n");
return 1;
}
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET) {
printf("socket failed: %d\\n", WSAGetLastError());
WSACleanup();
return 1;
}
if (getsockopt(s, SOL_SOCKET, SO_RCVBUF, (char*)&recvBufSize, &optLen) == SOCKET_ERROR) {
printf("getsockopt failed: %d\\n", WSAGetLastError());
} else {
printf("Receive buffer size: %d bytes\\n", recvBufSize);
}
closesocket(s);
WSACleanup();
return 0;
}