要在Arduino ESP8266上获取自己的公网IP,可以通过访问一个提供IP地址查询服务的API。
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting...");
}
Serial.println("Connected!");
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin("http://api.ipify.org");
int httpCode = http.GET();
if (httpCode > 0) {
String ip = http.getString();
Serial.println("Your public IP is: " + ip);
} else {
Serial.println("Error on HTTP request");
}
http.end();
}
}
void loop() {
// put your main code here, to run repeatedly:
}
|