ESP32 WebServer Library -headerName()

Home / References / ESP32 Library / WebServer Library

Description

The headerName() method is used to retrieve the names of HTTP request headers that have been collected by the ESP32 WebServer. This method provides access to header names based on their index position in the collected headers list. It works in conjunction with the header() method to enable complete header inspection – while header() returns header values, headerName() returns the corresponding header names. This method is particularly useful for iterating through all collected headers when you need to examine both names and values, or when implementing debugging and logging functionality.


Syntax and Usage

The headerName() method has only one usage pattern:

  • By header index: server.headerName(index) – Retrieves the name of a header at a specific index position. The index is zero-based and should be within the range of collected headers.

Arguments

  • index (int) – The zero-based index of the header whose name you want to retrieve. This should be between 0 and server.headers() - 1. Use the headers() method to determine the total number of available headers before calling headerName().

Return Value

The headerName() method returns a String containing the name of the requested header. If the index is out of range (negative or greater than the number of collected headers), the method returns an empty string (“”).


Example Codes

Example 1: Basic Header Name Retrieval

This example demonstrates the fundamental usage of headerName() to retrieve and display all collected header names along with their values.

How to use this example: Upload this code to your ESP32 and replace the WiFi credentials. After connecting, visit the ESP32’s IP address in your browser. The server will display all collected header names and their corresponding values. Try accessing with different browsers or tools like curl to see how header sets vary: curl -H "Custom-Header: test-value" http://ESP32_IP

/*
 * Author: Avant Maker
 * Date: June 16, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates the fundamental usage of headerName() to
 * retrieve and display all collected header names along with their values.
 * 
 * How to use this example: 
 * Upload this code to your ESP32 and replace the WiFi credentials. 
 * After connecting, visit the ESP32's IP address in your browser. 
 * The server will display all collected header names and their corresponding
 * values. Try accessing with different browsers or tools like curl to see
 * how header sets vary: curl -H "Custom-Header: test-value" http://ESP32_IP
 *
 * 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/home/all-about-esp32-arduino-core-library/
 *
 * 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 nnovative ideas to life.
 */

#include <WiFi.h>
#include <WebServer.h>

const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

WebServer server(80);

void handleRoot() {
  String message = "AvantMaker ESP32 Example: Header Names and Values\n";
  message += "==============================\n\n";
  
  int headerCount = server.headers();
  message += "Total headers collected: " + String(headerCount) + "\n\n";
  
  // Iterate through all headers using headerName() and header()
  for (int i = 0; i < headerCount; i++) {
    String name = server.headerName(i);
    String value = server.header(i);
    
    message += "Header " + String(i) + ":\n";
    message += "  Name:  " + name + "\n";
    message += "  Value: " + value + "\n\n";
  }
  
  if (headerCount == 0) {
    message += "No headers were collected.\n";
    message += "Headers must be configured with collectHeaders() first.\n";
  }
  
  server.send(200, "text/plain", message);
}

void setup() {
  Serial.begin(115200);
  
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  // Collect all headers to demonstrate headerName()
  server.collectAllHeaders();
  
  // Set up route handler
  server.on("/", handleRoot);
  
  // Start server
  server.begin();
  Serial.println("HTTP server started");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  server.handleClient();
}

Example 2: Header Analysis and Categorization

This example shows how to use headerName() to analyze and categorize headers, demonstrating practical applications for header inspection and processing.

How to use this example: After uploading and connecting to WiFi, visit the ESP32’s IP address to see the categorized header analysis. Test with different clients: browsers, curl, or mobile apps to see how header patterns differ. Access the /analyze endpoint to get detailed header categorization.

/*
 * Author: Avant Maker
 * Date: June 16, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example shows how to use headerName() to analyze and categorize
 * headers, demonstrating practical applications for header inspection
 * and processing.
 * 
 * How to use this example: 
 * After uploading and connecting to WiFi, visit the ESP32's IP
 * address to see the categorized header analysis. Test with different
 * clients: browsers, curl, or mobile apps to see how header patterns
 * differ. Access the /analyze endpoint to get detailed header categorization.
 *
 * 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/home/all-about-esp32-arduino-core-library/
 *
 * 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 nnovative ideas to life.
 */

#include <WiFi.h>
#include <WebServer.h>

const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

WebServer server(80);

void analyzeHeaders() {
  String message = "AvantMaker Header Analysis Report\n";
  message += "=====================\n\n";
  
  int headerCount = server.headers();
  int authHeaders = 0;
  int contentHeaders = 0;
  int cacheHeaders = 0;
  int customHeaders = 0;
  
  message += "Collected Headers (" + String(headerCount) + " total):\n";
  message += "----------------------------------------\n";
  
  for (int i = 0; i < headerCount; i++) {
    String headerName = server.headerName(i);
    String headerValue = server.header(i);
    
    // Categorize headers based on their names
    if (headerName.indexOf("Auth") != -1 || headerName.equals("Authorization")) {
      authHeaders++;
      message += "[AUTH] ";
    } else if (headerName.indexOf("Content") != -1 || headerName.indexOf("Accept") != -1) {
      contentHeaders++;
      message += "[CONTENT] ";
    } else if (headerName.indexOf("Cache") != -1 || headerName.indexOf("ETag") != -1 || 
               headerName.indexOf("Modified") != -1) {
      cacheHeaders++;
      message += "[CACHE] ";
    } else if (headerName.indexOf("X-") == 0 || headerName.indexOf("Custom") != -1) {
      customHeaders++;
      message += "[CUSTOM] ";
    } else {
      message += "[STANDARD] ";
    }
    
    message += headerName + ": " + headerValue + "\n";
  }
  
  message += "\nSummary:\n";
  message += "--------\n";
  message += "Authentication headers: " + String(authHeaders) + "\n";
  message += "Content-related headers: " + String(contentHeaders) + "\n";
  message += "Cache-related headers: " + String(cacheHeaders) + "\n";
  message += "Custom headers: " + String(customHeaders) + "\n";
  message += "Other standard headers: " + String(headerCount - authHeaders - contentHeaders - cacheHeaders - customHeaders) + "\n";
  
  server.send(200, "text/plain", message);
}

void handleRoot() {
  String html = "<html><body>";
  html += "<h1>AvantMaker ESP32 Header Analysis Tool</h1>";
  html += "<p>This tool analyzes and categorizes HTTP headers sent by your client.</p>";
  html += "<h2>Available Endpoints:</h2>";
  html += "<ul>";
  html += "<li><a href='/analyze'>/analyze</a> - Detailed header analysis</li>";
  html += "<li><a href='/count'>/count</a> - Quick header count</li>";
  html += "</ul>";
  html += "<p>Try sending custom headers with curl:<br>";
  html += "<code>curl -H \"X-Custom-Header: test\" -H \"Authorization: Bearer token\" http://" + WiFi.localIP().toString() + "/analyze</code></p>";
  html += "</body></html>";
  
  server.send(200, "text/html", html);
}

void handleCount() {
  String message = "Quick Header Count\n";
  message += "==================\n\n";
  
  int count = server.headers();
  message += "Total headers: " + String(count) + "\n\n";
  
  message += "Header names:\n";
  for (int i = 0; i < count; i++) {
    message += String(i + 1) + ". " + server.headerName(i) + "\n";
  }
  
  server.send(200, "text/plain", message);
}

void setup() {
  Serial.begin(115200);
  
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  // Collect all headers for comprehensive analysis
  server.collectAllHeaders();
  
  // Set up route handlers
  server.on("/", handleRoot);
  server.on("/analyze", analyzeHeaders);
  server.on("/count", handleCount);
  
  // Start server
  server.begin();
  Serial.println("HTTP server started");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  server.handleClient();
}

Example 3: Header Logging and Security Monitoring

This example demonstrates advanced usage of headerName() for implementing security monitoring and comprehensive request logging, showing real-world applications.

How to use this example: This creates a security monitoring system that logs all requests and analyzes headers for potential security concerns. Test with various scenarios: curl -H "X-Forwarded-For: 192.168.1.100" http://ESP32_IP/secure for proxy detection, or curl -H "User-Agent: SecurityScanner" http://ESP32_IP/secure for suspicious user agent detection. Check the Serial Monitor for detailed logs.

/*
 * Author: Avant Maker
 * Date: June 16, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates advanced usage of headerName()
 * for implementing security monitoring and comprehensive request
 * logging, showing real-world applications.
 * 
 * How to use this example: 
 * This creates a security monitoring system that logs all requests
 * and analyzes headers for potential security concerns. Test with 
 * various scenarios: 
 * curl -H "X-Forwarded-For: 192.168.1.100" http://ESP32_IP/secure
 * for proxy detection, or
 * curl -H "User-Agent: SecurityScanner" http://ESP32_IP/secure
 * for suspicious user agent detection.
 * Check the Serial Monitor for detailed logs.
 *
 * 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/home/all-about-esp32-arduino-core-library/
 *
 * 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 nnovative ideas to life.
 */

#include <WiFi.h>
#include <WebServer.h>

const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

WebServer server(80);

// Security monitoring functions
void logRequest() {
  Serial.println("=== REQUEST LOG ===");
  Serial.print("Timestamp: ");
  Serial.println(millis());
  Serial.print("Client IP: ");
  Serial.println(server.client().remoteIP());
  Serial.print("Method: ");
  Serial.println((server.method() == HTTP_GET) ? "GET" : 
                 (server.method() == HTTP_POST) ? "POST" : "OTHER");
  Serial.print("URI: ");
  Serial.println(server.uri());
  
  int headerCount = server.headers();
  Serial.print("Headers (");
  Serial.print(headerCount);
  Serial.println("):");
  
  for (int i = 0; i < headerCount; i++) {
    String name = server.headerName(i);
    String value = server.header(i);
    Serial.print("  ");
    Serial.print(name);
    Serial.print(": ");
    Serial.println(value);
  }
  Serial.println("==================");
}

bool checkSuspiciousHeaders() {
  int headerCount = server.headers();
  bool suspicious = false;
  
  for (int i = 0; i < headerCount; i++) {
    String name = server.headerName(i);
    String value = server.header(i);
    
    // Check for suspicious patterns
    if (name.indexOf("X-Forwarded") != -1 && value.indexOf("localhost") == -1) {
      Serial.println("WARNING: Proxy detected - " + name + ": " + value);
      suspicious = true;
    }
    
    if (name.equals("User-Agent") && 
        (value.indexOf("bot") != -1 || value.indexOf("crawler") != -1 || 
         value.indexOf("scanner") != -1)) {
      Serial.println("WARNING: Automated client detected - " + value);
      suspicious = true;
    }
    
    if (name.indexOf("X-") == 0 && value.length() > 100) {
      Serial.println("WARNING: Unusually long custom header - " + name);
      suspicious = true;
    }
  }
  
  return suspicious;
}

void handleSecure() {
  // Log all requests
  logRequest();
  
  // Check for suspicious activity
  bool suspicious = checkSuspiciousHeaders();
  
  String response = "Security Check Results\n";
  response += "======================\n\n";
  
  if (suspicious) {
    response += "⚠️  SECURITY ALERT: Suspicious headers detected!\n";
    response += "Check Serial Monitor for details.\n\n";
  } else {
    response += "✅ Headers appear normal.\n\n";
  }
  
  response += "Request Details:\n";
  response += "Client IP: " + server.client().remoteIP().toString() + "\n";
  response += "User Agent: " + server.header("User-Agent") + "\n";
  response += "Referer: " + server.header("Referer") + "\n";
  
  // List all header names for transparency
  response += "\nAll Header Names:\n";
  int count = server.headers();
  for (int i = 0; i < count; i++) {
    response += String(i + 1) + ". " + server.headerName(i) + "\n";
  }
  
  server.send(200, "text/plain", response);
}

void handleStats() {
  String response = "Header Statistics\n";
  response += "=================\n\n";
  
  int headerCount = server.headers();
  response += "Total headers in this request: " + String(headerCount) + "\n\n";
  
  // Count header types
  int standardHeaders = 0;
  int customHeaders = 0;
  
  for (int i = 0; i < headerCount; i++) {
    String name = server.headerName(i);
    if (name.indexOf("X-") == 0 || name.indexOf("Custom") != -1) {
      customHeaders++;
    } else {
      standardHeaders++;
    }
  }
  
  response += "Standard headers: " + String(standardHeaders) + "\n";
  response += "Custom headers: " + String(customHeaders) + "\n";
  response += "Custom header ratio: " + String((float)customHeaders / headerCount * 100) + "%\n";
  
  server.send(200, "text/plain", response);
}

void handleRoot() {
  String html = "<html><body>";
  html += "<h1>AvantMaker ESP32 Security Monitor</h1>";
  html += "<p>Monitoring and logging HTTP headers for security analysis.</p>";
  html += "<h2>Endpoints:</h2>";
  html += "<ul>";
  html += "<li><a href='/secure'>/secure</a> - Security check with detailed logging</li>";
  html += "<li><a href='/stats'>/stats</a> - Header statistics</li>";
  html += "</ul>";
  html += "<p><strong>Note:</strong> All requests are logged to Serial Monitor.</p>";
  html += "</body></html>";
  
  server.send(200, "text/html", html);
}

void setup() {
  Serial.begin(115200);
  
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  // Collect all headers for comprehensive monitoring
  server.collectAllHeaders();
  
  // Set up route handlers
  server.on("/", handleRoot);
  server.on("/secure", handleSecure);
  server.on("/stats", handleStats);
  
  // Start server
  server.begin();
  Serial.println("HTTP server started");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Security monitoring active - check Serial Monitor for logs");
}

void loop() {
  server.handleClient();
}
error: Content is protected !!