ESP32 WiFiClient Library – setSocketOption

Home / References / ESP32 Library / WiFiClientSecure

Description

The setSocketOption() method in the ESP32 WiFiClient Library allows you to configure low-level socket options for a network connection. This powerful tool empowers makers and enthusiasts to fine-tune the behavior of their ESP32’s WiFi connections, such as adjusting timeouts or enabling features like TCP_NODELAY. It’s ideal for advanced projects requiring precise control over network performance.


Syntax and Usage

The setSocketOption() method has two overloaded forms, each with different arguments to set socket options at varying levels of specificity. Below are the usage variations:

Basic Usage with Option, Value, and Length

int result = client.setSocketOption(option, value, len);

This form sets a socket option using a specific option identifier, a pointer to the value, and the length of that value. It’s useful for common socket tweaks like setting timeouts.

Advanced Usage with Level, Option, Value, and Length

int result = client.setSocketOption(level, option, value, len);

This form provides more control by specifying the protocol level (e.g., SOL_SOCKET or IPPROTO_TCP) alongside the option, value, and length. It’s suited for detailed configurations like disabling Nagle’s algorithm.

For practical applications and examples of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.


Argument(s)

The setSocketOption() method requires arguments, which differ based on the usage. Here’s a breakdown for each form:

  • Basic Usage:
    • option (int): The socket option to set (e.g., SO_RCVTIMEO for receive timeout).
    • value (char*): Pointer to the value to set for the option.
    • len (size_t): Length of the value in bytes.
  • Advanced Usage:
    • level (int): The protocol level at which the option resides (e.g., SOL_SOCKET or IPPROTO_TCP).
    • option (int): The specific socket option to set (e.g., SO_REUSEADDR or TCP_NODELAY).
    • value (const void*): Pointer to the value to set for the option.
    • len (size_t): Length of the value in bytes.

Return Value

The setSocketOption() method returns an integer indicating the success or failure of the operation:

  • 0: Success—the socket option was set correctly.
  • -1: Failure—an error occurred (e.g., invalid socket, unsupported option, or system error). Check the errno for details.

Example Codes

Below are examples demonstrating both ways of using setSocketOption() in practical ESP32 projects. Each connects to www.httpbin.org to illustrate real-world application.

Setting a Receive Timeout (Basic Usage)

This sketch sets a receive timeout on the socket to ensure the client doesn’t hang indefinitely waiting for data, enhancing reliability in network communication.

Explanation: After connecting to www.httpbin.org, the sketch uses setSocketOption() with SO_RCVTIMEO to set a 5-second receive timeout. The <lwip/sockets.h> header is included to define SO_RCVTIMEO, and the timeout value is passed as a struct timeval. The result is checked to confirm success, ensuring the client won’t wait indefinitely for a response—a practical tweak for robust network applications.

/*
 * Author: Avant Maker
 * Date: February 24, 2025
 * Version: 1.0
 * Description: This example demonstrates how to use 
 * ESP32 WiFiClient Library's setSocketOption method to 
 * set a receive timeout on the socket to ensure the client
 * doesn’t hang indefinitely waiting for data, enhancing
 * reliability in network communication.
 *
 * License: MIT 
 * 
 * Code Source: This example code is sourced from the Comprehensive 
 * Guide to the ESP32 Arduino Core Library, accessible on 
 * AvantMaker.com. For additional code examples and in-depth 
 * documentation related to the ESP32 Arduino Core Library, 
 * please visit:
 *
 * https://avantmaker.com/references/esp32-arduino-core-index/
 *
 * AvantMaker.com, your premier destination for all things 
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated 
 * to empowering makers, learners, and enthusiasts with the resources
 * they need to bring their innovative ideas to life.
 */
 
 #include <WiFi.h>
#include <lwip/sockets.h> // For SO_RCVTIMEO definition

// WiFi credentials
const char* ssid = "your-SSID";          // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD";  // Replace with your Wi-Fi password

// Server details
const char* host = "www.httpbin.org";
const int port = 80;

WiFiClient client;

void setup() {
    Serial.begin(115200);

    // Connect to WiFi
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nWiFi connected");

    // Connect to the server
    if (client.connect(host, port)) {
        Serial.println("Connected to server");

        // Set receive timeout to 5 seconds
        struct timeval timeout = {5, 0}; // 5 seconds, 0 microseconds
        int result = client.setSocketOption(SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
        if (result == 0) {
            Serial.println("Receive timeout set successfully");
        } else {
            Serial.println("Failed to set receive timeout");
        }

        // Send a GET request
        client.println("GET /get HTTP/1.1");
        client.println("Host: www.httpbin.org");
        client.println("Connection: close");
        client.println();
    } else {
        Serial.println("Connection failed");
    }
}

void loop() {
    if (client.available()) {
        Serial.print((char)client.read());
    }
    if (!client.connected()) {
        Serial.println("Disconnected");
        client.stop();
        while (true) delay(1000);
    }
}

ESP32 Library Index

ESP32 Arduino Core Library


FAQ

Ready to experiment and explore more about ESP32? Visit our website’s All About ESP32 Resources Hub, packed with tutorials, guides, and tools to inspire your maker journey. Experiment, explore, and elevate your skills with everything you need to master this powerful microcontroller platform!

error: Content is protected !!