getsockopt

The getsockopt function retrieves an option associated with a socket.

INT getsockopt( SOCKET s, int level, int optname, char *optval, int *optlen );

Parameters

Return Value

If the call completes successfully, getsockopt returns zero, and the buffer pointed to by the optval parameter contains the value of the requested option.

If the call fails, a socket error occurs, and getsockopt returns SOCKET_ERROR. For a specific error code, call WSAGetLastError.

Remarks

The getsockopt function is used to retrieve various options that can be set with setsockopt. The available options are defined by the protocol level and the option name. Common socket options include:

For a comprehensive list of options and their corresponding structures, refer to the Socket Options documentation.

Example Usage


#include <winsock2.h>
#include <ws2tcpip.h>

#pragma comment(lib, "ws2_32.lib")

int main() {
    WSADATA wsaData;
    SOCKET clientSocket;
    int optval;
    int optlen = sizeof(optval);

    // Initialize Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        // Handle error
        return 1;
    }

    // Create a socket (example: TCP)
    clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (clientSocket == INVALID_SOCKET) {
        // Handle error
        WSACleanup();
        return 1;
    }

    // Retrieve the SO_MAX_MSG_SIZE option
    if (getsockopt(clientSocket, SOL_SOCKET, SO_MAX_MSG_SIZE, (char*)&optval, &optlen) == SOCKET_ERROR) {
        // Handle error
        closesocket(clientSocket);
        WSACleanup();
        return 1;
    }

    // Process the retrieved option value
    printf("SO_MAX_MSG_SIZE: %d\n", optval);

    // Clean up
    closesocket(clientSocket);
    WSACleanup();
    return 0;
}
                

See Also