Advertisement
Open Source Projects by Phil Schwartz

Detecting dynamic DNS address changes with Python

A dynamic DNS hostname is useful only when its address tracks the public endpoint people must reach. That endpoint can change when an Australian router reconnects, the ISP renews a lease, or NBN equipment reboots. A small Python monitor makes the transition visible instead of leaving an outage to be found by chance.

The script must separate two observations: the public IP seen outside the network and the address published for the hostname. A changed public address is an event, while a mismatch may indicate a stale update. Treating every mismatch as a new outage creates noisy alerts while resolver caches catch up.

For an open-source utility, Python’s standard library is enough for a compact first version. urllib can retrieve the external address, socket can inspect DNS, ipaddress validates addresses, and JSON preserves the last observation. This makes the monitor easy to place on a Raspberry Pi or low-power Linux host in a Melbourne home office.

Checks can run every five or ten minutes and report state transitions. Temporary resolver or network failures should be logged without replacing the last known-good value. With those boundaries, the monitor becomes a dependable diagnostic rather than a background service that fails quietly.

Why Australian addresses change

Australian fixed-line broadband makes this practical. NBN services in Sydney, Melbourne, Brisbane and regional centres may terminate on FTTN or FTTP, with the provider router and network equipment handling the WAN connection. A power interruption, reboot or lease renewal can replace the external IPv4 address without any change inside the house.

Some Australian connections use carrier-grade NAT, sharing a public IPv4 address among customers. Binding a personal hostname to that shared address can point at the wrong gateway and defeat the intended port forwarding. Routed IPv6 behaves differently because each customer may receive a prefix, so A and AAAA records need separate rules.

Defining a reliable state

Define the authoritative address first. For a home gateway, an HTTPS endpoint returning the caller’s public IPv4 is enough, provided the machine sits behind the same NAT as the published service. Treat that endpoint as a dependency, check its privacy policy and allow it to be replaced.

Define “published” as well. A recursive resolver may return a cached answer, while the provider API shows the record most recently written. Proxied or load-balanced names can return provider addresses rather than the home connection. Store the public IP, A and AAAA values, check time and previous state.

Building the detector in Python

Here is a standard-library IPv4 baseline for a directly published hostname. It establishes a baseline, logs public-address changes and reports stale DNS transitions.

from datetime import datetime
from ipaddress import ip_address
from pathlib import Path
from zoneinfo import ZoneInfo
import json
import logging
import socket
import urllib.request

HOSTNAME = "home.example.com.au"
IP_ENDPOINT = "https://api4.ipify.org"
STATE_FILE = Path.home() / ".local/state/ddns-monitor.json"

logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger("ddns-monitor")


def stamp():
    return datetime.now(ZoneInfo("Australia/Sydney")).strftime(
        "%d/%m/%Y %H:%M:%S %Z"
    )


def public_ipv4():
    request = urllib.request.Request(
        IP_ENDPOINT,
        headers={"User-Agent": "ddns-monitor/1.0"},
    )
    with urllib.request.urlopen(request, timeout=15) as response:
        address = ip_address(response.read().decode("ascii").strip())
        if address.version != 4:
            raise ValueError("Expected an IPv4 address")
        return str(address)


def published_ipv4():
    results = socket.getaddrinfo(
        HOSTNAME, 443, socket.AF_INET, socket.SOCK_STREAM
    )
    return sorted({result[4][0] for result in results})


def check():
    try:
        current = public_ipv4()
        published = published_ipv4()
        state = (
            json.loads(STATE_FILE.read_text(encoding="utf-8"))
            if STATE_FILE.exists()
            else {}
        )
    except (OSError, ValueError) as error:
        log.error("%s Address check failed: %s", stamp(), error)
        return 1

    previous = state.get("public_ipv4")
    stale = current not in published
    now = datetime.now(ZoneInfo("Australia/Sydney"))

    if previous is None:
        log.info(
            "%s Baseline: public %s; DNS %s",
            stamp(), current, ", ".join(published),
        )
    elif current != previous:
        log.warning(
            "%s Public IPv4 changed from %s to %s",
            stamp(), previous, current,
        )

    if previous is not None and published != state.get("dns_ipv4", []):
        log.warning(
            "%s Published IPv4 changed to %s",
            stamp(), ", ".join(published),
        )

    if previous is not None and stale != state.get("stale"):
        log.error(
            "%s DDNS record is %s",
            stamp(), "stale" if stale else "synchronised",
        )

    payload = {
        "public_ipv4": current,
        "dns_ipv4": published,
        "stale": stale,
        "checked_at": now.isoformat(),
    }
    STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
    temporary = STATE_FILE.with_suffix(".tmp")
    temporary.write_text(json.dumps(payload, indent=2), encoding="utf-8")
    temporary.replace(STATE_FILE)
    return 0


if __name__ == "__main__":
    raise SystemExit(check())

The state file is replaced atomically, preventing truncated JSON after an interrupted write. The Australia/Sydney zone handles AEST and AEDT automatically, while alerts use the Australian DD/MM/YYYY date and JSON retains an ISO timestamp.

The DNS lookup is intentionally simple. For unattended use, query the provider API or use dnspython to query an authoritative nameserver, and treat a failed lookup as a failed check. Preserve the last successful sample during an outage so a resolver problem does not resemble a fresh change.

Reporting meaningful events

A useful report names the hostname, shows the previous and current public addresses, and distinguishes a public change from a DNS publication change. “home.example.com.au moved from 203.0.113.10 to 203.0.113.25” is actionable; “DNS error” is not. Include the check time and stale status.

Send routine observations to standard output for systemd’s journal, and reserve email or webhook alerts for transitions. Keep API tokens in a protected environment file, never in source control or command-line arguments. A webhook can feed a small-business LAN dashboard, while email suits a household Raspberry Pi.

The same transition model works for other host metrics. filesystem quota monitoring follows a similar pattern: establish a baseline, compare each sample, and report meaningful state changes instead of repeating the message on every poll.

Avoiding false change alerts

Separate a real change from a change of view. Public-address services may use different egress routes, DNS can use round-robin records, and an IPv6 privacy address can rotate even when the home prefix is unchanged. Track each family independently and decide whether the target is a specific host, a prefix or a stable service address.

Preserve state on errors and prevent overlapping runs. Retry transient failures with bounded backoff, fall back to a second endpoint, and let the DDNS updater finish before checking. A systemd timer with a suitable lock stops two processes writing the same JSON file after a delayed run.

Running the monitor locally

Install the script and configuration under a dedicated service account, then use a systemd timer or cron at a fixed interval. A .com.au or .au hostname managed through an Australian registrar gives the monitor a local-market use case, especially when the registrar supplies an API for updating its record.

On a broadband-connected NAS or mini PC in a Sydney or Melbourne home, keep alerts brief and retain enough history to show when the address last moved. Confirm how port forwarding behaves under CGNAT, or whether IPv6 permits direct access, before treating DDNS as a remote-access mechanism. The monitor then provides a clear audit trail without exposing credentials.