ESP32 WiFiClient Library – connect

Home / References / ESP32 Library / WiFiClientSecure

Description

The connect method in the WiFiClient library is used to establish a TCP connection to a specified server. This is a fundamental function for creating client-server communication over Wi-Fi with the ESP32, enabling your projects to interact with remote servers or devices. Whether you’re sending data to a web service or fetching information, this method is your gateway to network connectivity.


Syntax and Usage

The connect method can be used in two distinct ways depending on how you specify the target server. Below are the available syntaxes:

Using Hostname and Port:

client.connect(host, port)

This version connects to a server using its hostname (e.g., “www.httpbin.org”) and a specified port number. It’s ideal when working with domain names resolved via DNS.

Using IP Address and Port:

client.connect(ip, port)

This version connects directly to a server using its IP address (as an IPAddress object) and port. It’s useful for local networks or when DNS resolution isn’t needed.

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)

  • host: A character string (e.g., "www.httpbin.org") representing the hostname of the server to connect to. Used only in the hostname version.
  • ip: An IPAddress object specifying the server’s IP address (e.g., IPAddress(192, 168, 1, 1)). Used only in the IP address version.
  • port: An integer representing the port number to connect to (e.g., 80 for HTTP). Common to both versions.

Return Value

The connect method returns an integer:

  • 1: Success—connection established.
  • 0: Failure—connection could not be established (e.g., server unreachable, invalid parameters, or network issues).

Example Codes

Below are example codes demonstrating each usage of the connect method. These examples assume your ESP32 is connected to a Wi-Fi network.

Example 1: Connecting Using Hostname

This example connects to www.httpbin.org on port 80 and sends a simple HTTP GET request. Upload this code to your ESP32, ensure it’s connected to Wi-Fi, and open the Serial Monitor at 115200 baud to see the response.

To use this code, replace “your_SSID” and “your_PASSWORD” with your Wi-Fi credentials. Upload the code to your ESP32 board, open the Serial Monitor, and observe the connection process and HTTP response. Ensure the device has internet access for successful execution.

/*
 * Author: Avant Maker
 * Date: February 24, 2025
 * Version: 1.0
 * Description: This example demonstrates how to use
 * connect method to connect to www.httpbin.org on
 * port 80 and send a simple HTTP GET request. 
 *
 * 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>

const char* ssid = "your-SSID";         // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD"; // Replace with your Wi-Fi password
const char* host = "www.httpbin.org";
const int port = 80;

WiFiClient client;

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nConnected to Wi-Fi");

    if (client.connect(host, port)) {
        Serial.println("Connected to server");
        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() {
    while (client.available()) {
        String line = client.readStringUntil('\n');
        Serial.println(line);
    }
    if (!client.connected()) {
        client.stop();
        while (true); // Stop after one run for demo
    }
}

Example 2: Connecting Using IP Address

This example connects to an example IP address and sends an HTTP GET request. Replace the IP with a valid one if testing locally. Upload this code, connect to Wi-Fi, and monitor the Serial output.

Please note: this code is for demo only. The IP is not connectable.

/*
 * Author: Avant Maker
 * Date: February 24, 2025
 * Version: 1.0
 * Description: This example demonstrates how to use
 * connect method to connect to an Example IP on
 * port 80 and send a simple HTTP GET request. 
 * Please note: this code is for demo only. The IP is not
 * connectable.
 *
 * 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>

const char* ssid = "your-SSID";         // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD"; // Replace with your Wi-Fi password
IPAddress serverIP(34, 224, 252, 186);  // Example IP
const int port = 80;

WiFiClient client;

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nConnected to Wi-Fi");

    if (client.connect(serverIP, port)) {
        Serial.println("Connected to server");
        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() {
    while (client.available()) {
        String line = client.readStringUntil('\n');
        Serial.println(line);
    }
    if (!client.connected()) {
        client.stop();
        while (true); // Stop after one run for demo
    }
}

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 !!