Update Cloudflare DNS
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>
// ตั้งค่า WiFi
const char* ssid = "XXXX";
const char* password = "XXXX";
// ตั้งค่า Cloudflare API
const String cf_api_token = "XXXX";
const String cf_zone_id = "XXXX";
const String cf_record_id = "XXXX";
const String cf_domain = "XXXX"; // example.com or sub.example.com
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!");
updateDNS();
}
void loop() {
delay(600000);
updateDNS();
}
void updateDNS() {
if (WiFi.status() == WL_CONNECTED) {
std::unique_ptr<BearSSL::WiFiClientSecure> client(new BearSSL::WiFiClientSecure);
client->setInsecure(); // ไม่ตรวจสอบใบรับรอง SSL (ไม่แนะนำใน production)
HTTPClient https;
https.begin(*client, "https://api.ipify.org");
int httpCode = https.GET();
if (httpCode > 0) {
String publicIP = https.getString();
Serial.println("Public IP: " + publicIP);
String url = "https://api.cloudflare.com/client/v4/zones/" + cf_zone_id + "/dns_records/" + cf_record_id;
Serial.println(url);
String payload = "{\"type\":\"A\",\"name\":\"" + cf_domain + "\",\"content\":\"" + publicIP + "\",\"ttl\":120,\"proxied\":false}";
Serial.println(payload);
https.begin(*client, url);
https.addHeader("Content-Type", "application/json");
https.addHeader("Authorization", "Bearer " + cf_api_token);
int responseCode = https.PATCH(payload);
String response = https.getString();
Serial.println("Response Code: " + String(responseCode));
Serial.println("Response: " + response);
} else {
Serial.println("Error getting public IP");
}
https.end();
} else {
Serial.println("Not connected to WiFi");
}
}
Last updated