How do I set socket options and timeouts on Windows in C++?

Setting socket options and timeouts in C++ on Windows can be essential for managing network communications effectively. This guide will walk you through the necessary steps to configure socket options such as timeouts, enabling you to optimize connection behavior and data handling.

socket options, C++, Windows, timeouts, network programming, setsockopt, getpeername, SO_RCVTIMEO, SO_SNDTIMEO

This article explains how to set socket options and establish timeouts with socket programming in C++ on Windows, enhancing networking performance.


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

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

int main() {
    WSADATA wsaData;
    SOCKET sock;
    struct sockaddr_in server;

    // Initialize Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        std::cerr << "Failed to initialize Winsock." << std::endl;
        return 1;
    }

    // Create a socket
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == INVALID_SOCKET) {
        std::cerr << "Error creating socket." << std::endl;
        WSACleanup();
        return 1;
    }

    // Set socket options for send and receive timeouts
    int recvTimeout = 5000; // 5 seconds
    int sendTimeout = 5000; // 5 seconds

    setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&recvTimeout, sizeof(recvTimeout));
    setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char*)&sendTimeout, sizeof(sendTimeout));

    // Configure server address
    server.sin_family = AF_INET;
    server.sin_port = htons(8080);
    server.sin_addr.s_addr = inet_addr("127.0.0.1");

    // Connect to server
    if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0) {
        std::cerr << "Failed to connect to server." << std::endl;
    } else {
        std::cout << "Connected to server." << std::endl;
    }

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

socket options C++ Windows timeouts network programming setsockopt getpeername SO_RCVTIMEO SO_SNDTIMEO