Dynamic DNS Made Easy: Building a Python-Based Solution

CK CK 3788 
Created at  
796 0 0

Creating a dynamic DNS (Domain Name System) service in Python involves several components: a server that listens for DNS queries, a database to store mappings between domain names and IP addresses, and functionality to update these mappings dynamically. Below is a simple example of a Python-based dynamic DNS service using Flask, a lightweight web framework, and SQLite, a simple SQL database.

from flask import Flask, request, jsonify
import sqlite3

app = Flask(__name__)
DATABASE = 'dns.db'

def init_db():
    conn = sqlite3.connect(DATABASE)
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS dns_records (
            domain TEXT PRIMARY KEY,
            ip_address TEXT
        )
    ''')
    conn.commit()
    conn.close()

@app.route('/update_dns', methods=['POST'])
def update_dns():
    data = request.get_json()
    domain = data.get('domain')
    ip_address = data.get('ip_address')
    
    if not domain or not ip_address:
        return jsonify({'message': 'Domain and IP address are required.'}), 400
    
    conn = sqlite3.connect(DATABASE)
    cursor = conn.cursor()
    
    cursor.execute('INSERT OR REPLACE INTO dns_records (domain, ip_address) VALUES (?, ?)', (domain, ip_address))
    conn.commit()
    conn.close()
    
    return jsonify({'message': f'DNS record for {domain} updated successfully.'})

@app.route('/resolve_dns', methods=['GET'])
def resolve_dns():
    domain = request.args.get('domain')
    
    if not domain:
        return jsonify({'message': 'Domain is required.'}), 400
    
    conn = sqlite3.connect(DATABASE)
    cursor = conn.cursor()
    
    cursor.execute('SELECT ip_address FROM dns_records WHERE domain=?', (domain,))
    result = cursor.fetchone()
    conn.close()
    
    if result:
        return jsonify({'ip_address': result[0]})
    else:
        return jsonify({'message': 'Domain not found.'}), 404

if __name__ == '__main__':
    init_db()
    app.run(debug=True)

This code sets up a basic Flask web application with two endpoints:

  1. /update_dns: This endpoint allows clients to update DNS records by sending a POST request with JSON data containing the domain name and corresponding IP address.
  2. /resolve_dns: This endpoint resolves DNS queries by accepting a domain name as a query parameter and returning the associated IP address.

The DNS records are stored in an SQLite database named dns.db. The init_db() function initializes the database by creating a table named dns_records if it doesn't already exist.

To run this code:

  1. Install Flask (pip install Flask).
  2. Save the code in a file (e.g., dynamic_dns.py).
  3. Run the file (python dynamic_dns.py).
  4. The server will start, and you can use tools like cURL or Postman to send requests to the /update_dns and /resolve_dns endpoints.

Please note that this example is for educational purposes and lacks several features found in a production-grade dynamic DNS service, such as authentication, rate limiting, and error handling.

Tags DNS Database Management Dynamic DNS Flask Networking Python SQLite Server Management Tutorial Web Development Facebook X
Comments 0
Similar posts
  1. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    739
  2. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,073
  3. Exploring the Depths of Data Transfer: sendfile vs. kTLS
    1,320
  4. Public DNS (Domain Name Service) based on IPv4, IPv6 widely used
    1,244
  5. Equal Height Blocks in Bootstrap with JavaScript
    711
  6. Mastering Excel Data Importation in PHP
    555
  7. Creating a Pinterest-Style Card Layout with Bootstrap and Masonry
    596
  8. Simple Example to get the total number of records in BigQuery with Python
    666
  9. Learning about Python Multiprocessing Technique
    592
  10. Python Flask web server tutorial from the scratch
    623
  11. Python Flask with simple HTML files to server web pages along with API
    927
  12. Python script to list files on your Google Drive and download one of them
    941
  13. Method to maximize full CPU performance with Python
    317
  14. Uploading a file to a Google Drive Folder programmatically with Python
    3,307
  15. How to run Python 3.9 on Mac?
    652
  16. Simple Java Code to display Hello, World on the web
    565
  17. Is PyTorch Dead? Deep Learning's Enduring Role Beyond LLMs & Essential Skills
    695
  18. A Python Code to get the Server Instance ID for Remote Management
    362
  19. Forecasting with Linear Regression and KNN Regression in Python
    926
  20. Uvicorn, Gunicorn: Proving Your Production Prowess
    399
  21. What Replaced JSP? Modern Java Web Dev Explained (with Examples)
    256
  22. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,159
  23. Harnessing the Power of Random Forest Algorithm in Python
    658
  24. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    634
  25. Python Implementation of Linear Regression
    840
  26. Configuring IP Address on Centos 6.7
    791
  27. Retrieving all image links from an HTML document
    419
  28. List All Network Drives
    392
  29. How to set the "home page" for the Internet Explorer from Delphi code
    431
  30. How to get get IE favorites
    454
  1. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    441
  2. Creating mp3 audio file based on the text input with Python
    465
  3. Implementing Text To Speech / Audio with Python3 and pyttsx3
    355
  4. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  5. Python Simplified Assignment Operators
    533
  6. Trackback module used for Python Threading debugging
    843
  7. Simple Web Server based in Python
    373
  8. Thread Implementation in Python
    509
  9. A shell script that activates a Python virtual environment and then runs a specific Python script
    743
  10. Using BigQuery in Python
    412
  11. Python Web Programming based on Django from the Scratch
    374
  12. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    188
  13. How do I determine the client IP type in Python - IPv4 or IPv6
    763
  14. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,233
  15. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  16. Milvus & FAISS: Decoding Their ML Synergy
    279
  17. Save clustering result (aka dictionary) in JSON and Reuse loaded result
    378
  18. Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction
    1,435
  19. Mastering Random Forest Regression: A Comprehensive Guide with Python Examples
    1,098
  20. Simple Python Clustering Example based on the high school students' score
    340
  21. Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network
    800
  22. Memory Problems with Python Arrays? Discover Dask Array
    324
  23. Mastering Supervised Machine Learning with Python: A Comprehensive Guide
    1,058
  24. Mastering AI: A Beginner's Guide to Python Programming and Beyond
    1,035
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  3. How do I create animated background for Google Meet?
    21,012
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    251
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    515
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    232
  16. TPU & GPU Cluster Management Tools
    245
  17. The Concept of Scaffolding in AI Agents
    234
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    222
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    221
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  30. Understanding Data Lineage
    262