ESP32 - Get Public IP

#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";
  }
}

Last updated