The getsockopt function retrieves an option associated with a socket.
INT getsockopt( SOCKET s, int level, int optname, char *optval, int *optlen );
A descriptor that identifies a socket.
A constant that specifies the protocol level at which the option is defined. Use the SOL_SOCKET value to specify socket-level options.
A constant that specifies the socket option to retrieve. For a list of available options, see Socket Options.
A pointer to a buffer that receives the value of the requested option. The structure of this parameter depends on the option specified in the optname parameter.
A pointer to a variable that, on input, specifies the size of the buffer pointed to by optval, and on output, specifies the actual size of the value returned in optval.
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.
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:
SO_BROADCAST: Allows transmission of broadcast datagrams.SO_DEBUG: Enables or disables debugging information.SO_ERROR: Retrieves error information associated with the socket.SO_KEEPALIVE: Enables or disables keep-alive activity.SO_LINGER: Controls the behavior of socket closure.SO_RCVBUF: Sets the size of the buffer for receiving data.SO_REUSEADDR: Allows a socket to be bound to an address that is already in use.SO_SNDBUF: Sets the size of the buffer for sending data.SO_TYPE: Retrieves the type of the socket.For a comprehensive list of options and their corresponding structures, refer to the Socket Options documentation.
#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;
}