Dynamic DNS update with Arduino/ESP

Now you can easily make your IoT device send data to a DynamicDNS server (such as ddnames.com) and specify the current IP address. I give you the code which is just an example:

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

const char* ssid = "YourSSID";
const char* password = "YourWiFiPassword";
byte tries = 10;  // Trying to connect to wireless AP

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (--tries && WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  if (WiFi.status() != WL_CONNECTED)
  {
    Serial.println("Non Connecting to WiFi..");
  }
  else
  {
    // Connection established
    // Show local IP
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
  }
}

void loop() {
if (WiFi.status() == WL_CONNECTED) {
WiFiClient client;
HTTPClient http;
http.begin(client,"http://136.244.82.142/ip.php");
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println(payload);
http.end();
delay(3000);
HTTPClient http2;
http2.begin(client,"https://ddnames.com/update");
http2.addHeader("Content-Type", "application/json");
int httpCode2 = http2.POST("{\"email\":\"[email protected]\", \"apikey\":\"yourApikey\", \"domain\": \"yourdomain.tld\", \"ipaddress\": \""+ payload +"\"}");
String payload2 = http2.getString();
Serial.println(httpCode2);
Serial.println(payload2);
Serial.println("{\"email\":\"[email protected]\", \"apikey\":\"yourApikey\", \"domain\": \"yourdomain.tld\", \"ipaddress\": \""+ payload +"\"}");
http2.end();
}}
delay(5000)

This program is designed to find out the current IP address and then send it to a server to update the DNS record for a specified domain. The program first attempts to connect to a wireless access point using the provided SSID and password, with a limit of 10 attempts. If the connection is successful, the program shows the local IP address and proceeds to the main loop.

See also  Linux Ubuntu Raspberry PI temperature control script

In the main loop, the program checks if the wireless connection is still active. If the connection is active, the program creates a client and an HTTP request to get the current IP address from a specific URL. If the request is successful, the program then sends a second HTTP request to update the DNS record for the specified domain, using the retrieved IP address as the new value for the record. The program uses a delay of 5 seconds between each iteration of the loop.

Overall, this program is useful for updating the DNS record for a domain with a dynamic IP address, ensuring that the domain always points to the correct IP address even if it changes.

See also  Form with different action buttons and request on the same page. Django

 

Author: admin

Leave a Reply

Your email address will not be published. Required fields are marked *