惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

爱范儿
爱范儿
Simon Willison's Weblog
Simon Willison's Weblog
K
Kaspersky official blog
P
Palo Alto Networks Blog
Google DeepMind News
Google DeepMind News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
AI
AI
G
GRAHAM CLULEY
O
OpenAI News
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Help Net Security
Help Net Security
L
LINUX DO - 热门话题
S
Schneier on Security
P
Privacy International News Feed
L
Lohrmann on Cybersecurity
SecWiki News
SecWiki News
C
Cybersecurity and Infrastructure Security Agency CISA
T
Threatpost
C
Cyber Attacks, Cyber Crime and Cyber Security
A
Arctic Wolf
C
Cisco Blogs
V2EX - 技术
V2EX - 技术
有赞技术团队
有赞技术团队
Apple Machine Learning Research
Apple Machine Learning Research
月光博客
月光博客
Latest news
Latest news
人人都是产品经理
人人都是产品经理
Schneier on Security
Schneier on Security
Last Week in AI
Last Week in AI
Webroot Blog
Webroot Blog
美团技术团队
N
News and Events Feed by Topic
大猫的无限游戏
大猫的无限游戏
Security Archives - TechRepublic
Security Archives - TechRepublic
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 三生石上(FineUI控件)
The Cloudflare Blog
Project Zero
Project Zero
博客园_首页
Cloudbric
Cloudbric
IT之家
IT之家
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
罗磊的独立博客
Hacker News: Ask HN
Hacker News: Ask HN
The Last Watchdog
The Last Watchdog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tenable Blog
Scott Helme
Scott Helme

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to build a DDNS updater with no API key
Vix · 2026-06-24 · via DEV Community

Vix

How to build a DDNS updater with no API key

Dynamic DNS (DDNS) is one of those problems that sounds simple — keep a DNS record pointing at your current IP — but tends to involve more moving parts than expected. Most solutions require creating an account, generating an API key, and depending on a third-party service to detect your own IP address. This article shows how to build a complete DDNS updater that detects your public IP without any API key, using IPPubblico.org as the IP detection layer.

The DDNS update step (writing to your DNS provider) still requires your DNS provider's credentials, but the IP detection part — which is what breaks or goes stale most often — is completely key-free.


How DDNS updaters work

The basic loop is always the same:

  1. Get your current public IP address
  2. Compare it to the last known IP (stored locally or retrieved from DNS)
  3. If it changed, update the DNS record
  4. Wait and repeat

The IP detection step (step 1) is where most updaters introduce unnecessary dependencies. Many use ip-api.com, ipify.org, or similar services that require rate limit management, API keys for higher tiers, or have unreliable uptime. IPPubblico returns a plain text response with no authentication overhead — ideal for scripts that run every few minutes.


Shell script (Linux / OpenWRT / router firmware)

The most portable version. Runs on any system with curl and a cron daemon — including OpenWRT routers, NAS devices, and embedded Linux boards.

#!/bin/sh
# ddns_updater.sh
# Detects public IP change and updates a Cloudflare DNS record

# --- Configuration ---
CF_API_TOKEN="your_cloudflare_api_token"
CF_ZONE_ID="your_zone_id"
CF_RECORD_ID="your_record_id"
CF_RECORD_NAME="home.yourdomain.com"
IP_CACHE_FILE="/tmp/ddns_last_ip.txt"
LOG_FILE="/var/log/ddns_updater.log"

# --- Functions ---
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

get_public_ip() {
    curl -s --max-time 10 https://ipv4.ippubblico.org/
}

update_cloudflare() {
    local NEW_IP="$1"
    curl -s -X PUT \
        "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/dns_records/${CF_RECORD_ID}" \
        -H "Authorization: Bearer ${CF_API_TOKEN}" \
        -H "Content-Type: application/json" \
        --data "{\"type\":\"A\",\"name\":\"${CF_RECORD_NAME}\",\"content\":\"${NEW_IP}\",\"ttl\":60}"
}

# --- Main ---
CURRENT_IP=$(get_public_ip)

if [ -z "$CURRENT_IP" ]; then
    log "ERROR: Failed to get public IP"
    exit 1
fi

LAST_IP=""
if [ -f "$IP_CACHE_FILE" ]; then
    LAST_IP=$(cat "$IP_CACHE_FILE")
fi

if [ "$CURRENT_IP" = "$LAST_IP" ]; then
    log "IP unchanged: $CURRENT_IP"
    exit 0
fi

log "IP changed: $LAST_IP -> $CURRENT_IP. Updating DNS..."

RESULT=$(update_cloudflare "$CURRENT_IP")

if echo "$RESULT" | grep -q '"success":true'; then
    echo "$CURRENT_IP" > "$IP_CACHE_FILE"
    log "DNS updated successfully to $CURRENT_IP"
else
    log "ERROR: DNS update failed. Response: $RESULT"
    exit 1
fi

Add to cron (runs every 5 minutes):

*/5 * * * * /usr/local/bin/ddns_updater.sh


Python (cross-platform)

A more robust version with proper error handling, structured logging, and support for multiple DNS providers.

#!/usr/bin/env python3
# ddns_updater.py

import requests
import json
import logging
import time
from pathlib import Path
from dataclasses import dataclass
from typing import Optional

# --- Configuration ---
CLOUDFLARE_API_TOKEN = "your_cloudflare_api_token"
CLOUDFLARE_ZONE_ID   = "your_zone_id"
CLOUDFLARE_RECORD_ID = "your_record_id"
RECORD_NAME          = "home.yourdomain.com"
CACHE_FILE           = Path("/tmp/ddns_last_ip.txt")
CHECK_INTERVAL       = 300  # seconds

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(message)s',
    handlers=[
        logging.FileHandler('/var/log/ddns_updater.log'),
        logging.StreamHandler()
    ]
)
log = logging.getLogger(__name__)


def get_public_ip() -> Optional[str]:
    """Get current public IPv4 address — no API key required."""
    try:
        res = requests.get('https://ipv4.ippubblico.org/', timeout=10)
        res.raise_for_status()
        return res.text.strip()
    except requests.RequestException as e:
        log.error(f"Failed to get public IP: {e}")
        return None


def get_cached_ip() -> Optional[str]:
    try:
        return CACHE_FILE.read_text().strip()
    except FileNotFoundError:
        return None


def save_ip(ip: str) -> None:
    CACHE_FILE.write_text(ip)


def update_cloudflare(new_ip: str) -> bool:
    """Update an A record on Cloudflare."""
    url = f"https://api.cloudflare.com/client/v4/zones/{CLOUDFLARE_ZONE_ID}/dns_records/{CLOUDFLARE_RECORD_ID}"
    headers = {
        "Authorization": f"Bearer {CLOUDFLARE_API_TOKEN}",
        "Content-Type": "application/json",
    }
    payload = {
        "type": "A",
        "name": RECORD_NAME,
        "content": new_ip,
        "ttl": 60,
    }
    try:
        res = requests.put(url, headers=headers, json=payload, timeout=10)
        data = res.json()
        if data.get("success"):
            return True
        log.error(f"Cloudflare API error: {data.get('errors')}")
        return False
    except requests.RequestException as e:
        log.error(f"Cloudflare request failed: {e}")
        return False


def check_and_update() -> None:
    current_ip = get_public_ip()
    if not current_ip:
        return

    last_ip = get_cached_ip()

    if current_ip == last_ip:
        log.info(f"IP unchanged: {current_ip}")
        return

    log.info(f"IP changed: {last_ip or 'unknown'}{current_ip}")

    if update_cloudflare(current_ip):
        save_ip(current_ip)
        log.info(f"DNS updated successfully to {current_ip}")
    else:
        log.error("DNS update failed")


if __name__ == "__main__":
    log.info("DDNS updater started")
    while True:
        check_and_update()
        time.sleep(CHECK_INTERVAL)

Run as a systemd service:

[Unit]
Description=DDNS Updater
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/bin/python3 /usr/local/bin/ddns_updater.py
Restart=on-failure
RestartSec=30

[Install]
WantedBy=multi-user.target


Node.js

// ddns_updater.js — requires Node 18+
import fs   from 'fs/promises';
import path from 'path';

const CF_API_TOKEN  = 'your_cloudflare_api_token';
const CF_ZONE_ID    = 'your_zone_id';
const CF_RECORD_ID  = 'your_record_id';
const RECORD_NAME   = 'home.yourdomain.com';
const CACHE_FILE    = '/tmp/ddns_last_ip.txt';
const INTERVAL_MS   = 5 * 60 * 1000;

async function getPublicIP() {
  const res = await fetch('https://ipv4.ippubblico.org/', {
    signal: AbortSignal.timeout(10000)
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return (await res.text()).trim();
}

async function getCachedIP() {
  try { return (await fs.readFile(CACHE_FILE, 'utf-8')).trim(); }
  catch { return null; }
}

async function updateCloudflare(ip) {
  const res = await fetch(
    `https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/dns_records/${CF_RECORD_ID}`,
    {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${CF_API_TOKEN}`,
        'Content-Type':  'application/json',
      },
      body: JSON.stringify({ type: 'A', name: RECORD_NAME, content: ip, ttl: 60 }),
      signal: AbortSignal.timeout(10000),
    }
  );
  const data = await res.json();
  return data.success === true;
}

async function check() {
  try {
    const current = await getPublicIP();
    const last    = await getCachedIP();

    if (current === last) {
      console.log(`[${new Date().toISOString()}] IP unchanged: ${current}`);
      return;
    }

    console.log(`[${new Date().toISOString()}] IP changed: ${last ?? 'unknown'}${current}`);

    if (await updateCloudflare(current)) {
      await fs.writeFile(CACHE_FILE, current, 'utf-8');
      console.log(`[${new Date().toISOString()}] DNS updated to ${current}`);
    } else {
      console.error('DNS update failed');
    }
  } catch (err) {
    console.error('Error:', err.message);
  }
}

check();
setInterval(check, INTERVAL_MS);


Go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "log"
    "net/http"
    "os"
    "strings"
    "time"
)

const (
    cfAPIToken  = "your_cloudflare_api_token"
    cfZoneID    = "your_zone_id"
    cfRecordID  = "your_record_id"
    recordName  = "home.yourdomain.com"
    cacheFile   = "/tmp/ddns_last_ip.txt"
    checkInterval = 5 * time.Minute
)

func getPublicIP() (string, error) {
    client := &http.Client{Timeout: 10 * time.Second}
    resp, err := client.Get("https://ipv4.ippubblico.org/")
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    return strings.TrimSpace(string(body)), nil
}

func getCachedIP() string {
    data, err := os.ReadFile(cacheFile)
    if err != nil {
        return ""
    }
    return strings.TrimSpace(string(data))
}

func updateCloudflare(ip string) error {
    url := fmt.Sprintf(
        "https://api.cloudflare.com/client/v4/zones/%s/dns_records/%s",
        cfZoneID, cfRecordID,
    )
    payload := map[string]interface{}{
        "type":    "A",
        "name":    recordName,
        "content": ip,
        "ttl":     60,
    }
    body, _ := json.Marshal(payload)

    req, _ := http.NewRequest("PUT", url, bytes.NewReader(body))
    req.Header.Set("Authorization", "Bearer "+cfAPIToken)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{Timeout: 10 * time.Second}
    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    var result map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&result)
    if result["success"] != true {
        return fmt.Errorf("cloudflare error: %v", result["errors"])
    }
    return nil
}

func checkAndUpdate() {
    current, err := getPublicIP()
    if err != nil {
        log.Printf("Failed to get IP: %v", err)
        return
    }

    last := getCachedIP()
    if current == last {
        log.Printf("IP unchanged: %s", current)
        return
    }

    log.Printf("IP changed: %s → %s", last, current)

    if err := updateCloudflare(current); err != nil {
        log.Printf("DNS update failed: %v", err)
        return
    }

    os.WriteFile(cacheFile, []byte(current), 0644)
    log.Printf("DNS updated to %s", current)
}

func main() {
    log.Println("DDNS updater started")
    checkAndUpdate()
    for range time.Tick(checkInterval) {
        checkAndUpdate()
    }
}


How the IP detection works

All examples use https://ipv4.ippubblico.org/ — a dedicated endpoint that forces an IPv4 connection and returns nothing but the bare IP address as plain text. This makes parsing trivial in every language:

203.0.113.42

No JSON to unwrap, no status fields to check, no authentication headers. For a script that runs every 5 minutes, this simplicity matters — fewer things to break.

If you want to verify DNS propagation after an update (checking that the IP in the DNS matches your current IP), a quick way to confirm your current IP without a DNS lookup:

CURRENT=$(curl -s https://ipv4.ippubblico.org/)
DNS_IP=$(dig +short home.yourdomain.com @8.8.8.8)
echo "Current IP : $CURRENT"
echo "DNS record : $DNS_IP"
[ "$CURRENT" = "$DNS_IP" ] && echo "In sync" || echo "Update pending"


What about IPv6?

If your setup supports IPv6 and your DNS provider supports AAAA records, you can detect the IPv6 address the same way:

IPV6=$(curl -s https://ipv6.ippubblico.org/)
# Returns the IPv6 address or nothing if not available

If the endpoint returns an empty response or fails to connect, the client has no IPv6 connectivity — handle it gracefully and fall back to IPv4 only.


Summary

Language Dependency Runs as
Shell curl cron / init script
Python requests systemd service / cron
Node.js none (native fetch) systemd service / PM2
Go none (stdlib) systemd service / binary

IP detection across all examples: https://ipv4.ippubblico.org/ — no API key, no account, plain text response.

Full documentation: ippubblico.org/docs.html


Which DNS provider are you using for DDNS? Share your setup in the comments.