# ESP32 - Get Public IP

```cpp
#include <WiFi.h>
#include <HTTPClient.h>

// ตั้งค่า WiFi
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  Serial.print("Connecting to WiFi...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println(" Connected!");

  // ดึง Public IP Address
  String publicIP = getPublicIP();
  Serial.println("Public IP: " + publicIP);
}

void loop() {
  // ดึง Public IP Address ทุกๆ 10 นาที
  delay(600000);
  String publicIP = getPublicIP();
  Serial.println("Public IP: " + publicIP);
}

String getPublicIP() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("http://api.ipify.org"); // หรือใช้ https://ipinfo.io/ip สำหรับบริการอื่น
    int httpCode = http.GET();

    if (httpCode > 0) {
      String publicIP = http.getString();
      http.end();
      return publicIP;
    } else {
      Serial.println("Error getting public IP");
      http.end();
      return "Error";
    }
  } else {
    Serial.println("Not connected to WiFi");
    return "Not Connected";
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://code.cyberchamp.net/esp32-esp8266/esp32-get-public-ip.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
