ESP32 WiFiClient Library – localPort

Home / References / ESP32 Library / WiFiClientSecure

Description

The localPort method in the ESP32 WiFiClient Library returns the local port number assigned to the client’s side of an active TCP connection. This method is useful for debugging, logging, or understanding the network behavior of your ESP32 project, particularly when the system automatically assigns an ephemeral port.


Syntax and Usage

The localPort method is called on a WiFiClient object to retrieve the local port number. Below is the syntax and a code snippet demonstrating its usage:

uint16_t port = client.localPort();

Here’s how this method can be used:

  • Without Arguments: Invoke the method on an active WiFiClient instance to get the local port number as an integer.

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)

This method does not require any arguments. It operates based on the current connection state of the WiFiClient object.


Return Value

The localPort method returns an unsigned 16-bit integer (uint16_t) representing the local port number used by the ESP32 for the connection. If the client is not connected, it typically returns 0.


Example Codes

Below is an example demonstrating how to use the localPort method in a practical scenario. This corresponds to the usage outlined in Section 2.

Example: Retrieving and Displaying the Local Port Number

This example connects an ESP32 to www.httpbin.org on port 80, retrieves the local port number using localPort, and prints it to the Serial Monitor to illustrate the ESP32’s assigned port.

/*
 * Author: Avant Maker
 * Date: February 24, 2025
 * Version: 1.0
 * Description: This example connects an ESP32
 * to www.httpbin.org on port 80, retrieves
 *  the local port number using ESP32 WiFiClient
 * Library's localPort method, and prints it to
 * the Serial Monitor to illustrate the ESP32’s
 * assigned port.
 
 This example demonstrates how to use 
 * ESP32 WiFiClient Library's available method to
 
 * 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;

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

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

    // Create a WiFiClient instance
    WiFiClient client;

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

        // Get the local port number
        uint16_t localPortNum = client.localPort();
        Serial.print("Local Port Number: ");
        Serial.println(localPortNum);

        // Send HTTP GET request
        client.println("GET /get HTTP/1.1");
        client.println("Host: www.httpbin.org");
        client.println("Connection: close");
        client.println();

        // Wait for server response
        while (client.connected()) {
            if (client.available()) {
                String line = client.readStringUntil('\n');
                Serial.println(line);
            }
        }
        client.stop();
        Serial.println("Disconnected");
    } else {
        Serial.println("Connection failed");
    }
}

void loop() {
    // Nothing to do here
}

Explanation: The ESP32 connects to a WiFi network and establishes a TCP connection to www.httpbin.org on port 80. The localPort method retrieves the ephemeral port number assigned to the ESP32’s side of the connection (typically a high-numbered port like 49152–65535), which is then printed to the Serial Monitor. This helps makers understand their device’s network configuration before sending an HTTP request.

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