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