Skip to content

Instantly share code, notes, and snippets.

Created July 25, 2021 17:46
What would you like to do?
A simple python script for updating DNS zones using IPv6 and Dynv6's REST API
# Imports
import requests
import socket
import time
import traceback
import os
# Constants
HOSTNAME = "....."
TOKEN = "......"
GOOGLE_IPv6_DNS = "2001:4860:4860::8888"
# Utility functions
def getPublicIpAddress():
# Create a udp ipv6 socket and connects with Google's ipv6 primary dns server
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
s.connect((GOOGLE_IPv6_DNS, 80))
# Gets the socket ipv6
ip = s.getsockname()[0]
# Closes the socket
print(f"Public IP: {ip}")
return ip
def updateDynv6(ip):
print(f"<- GET {ENDPOINT}?token={TOKEN}&hostname={HOSTNAME}&ipv6={ip}")
# Updates the route via REST API
response = requests.get(url=ENDPOINT, params={ 'token': TOKEN, 'hostname': HOSTNAME, 'ipv6': ip })
print(f"-> {response.status_code} {ENDPOINT}")
# Check whether the request was successful
return response.status_code == 200
def fetchPublicIpCache():
# Opens the cache.txt file, in order to not onerate the server by spamming requests and keeping track of the last ip request
# even when the script restarts
buffer = None
with open("./cache.txt", "r") as fp:
temp =
if temp != None and len(temp) > 0: buffer = temp
return buffer
def updatePublicIpCache(ip):
# Saves the new updated ip into the cache.txt file
with open("./cache.txt", "w+") as fp:
def main():
print("Starting dydns script...")
# Create cache file if not exists
if not os.path.exists("./cache.txt"):
# Get the current ip address
last_ip_address = fetchPublicIpCache()
print(f"Cached ip address: {last_ip_address}")
while True:
# Fetch the current ip address
current_ip_address = getPublicIpAddress()
# Detect whether it has changed and if the http request was successful
if last_ip_address != current_ip_address and updateDynv6(current_ip_address):
# Caches the new ip_address
print("Caching ip address...")
last_ip_address = current_ip_address
# Sleeps for two minutes before checking it again
# In case of errors, print 'em and exit with status 1
Copy link

It's specially useful when using as a system service
Like specifying a systemd service to always restart it whenever it crashes

** requires python 3 **

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment