Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records

CK CK 3788 
Created at  
1,073 0 0

Supporting AAAA records, which are used for IPv6 addresses, is a straightforward extension of the previous examples. The AAAA record type is essential for modern applications that operate over IPv6 networks. Here's how you can modify the existing Python DNS server example to handle AAAA records in addition to A, CNAME, and TXT records:

from socket import socket, AF_INET, SOCK_DGRAM
from dnslib import DNSRecord, RR, QTYPE, TXT

# Define DNS records (for demonstration purposes)
dns_records = {
    'example.com.': ('A', '192.168.1.100'),
    'ipv6.example.com.': ('AAAA', '2001:0db8:85a3:0000:0000:8a2e:0370:7334'),
    'sub.example.com.': ('A', '192.168.1.101'),
    'another.example.com.': ('A', '192.168.1.102'),
    'alias.example.com.': ('CNAME', 'example.com.'),
    'info.example.com.': ('TXT', 'This is a test TXT record'),
}

# Create UDP socket
sock = socket(AF_INET, SOCK_DGRAM)
sock.bind(('0.0.0.0', 53))  # Bind to port 53

# Handle DNS queries
while True:
    data, addr = sock.recvfrom(512)  # Buffer size is 512 bytes
    dns_request = DNSRecord.parse(data)

    # Prepare DNS response
    dns_response = DNSRecord(DNSRecord.HEADER.ID(dns_request.header.id))
    dns_response.add_question(dns_request.q.qname)

    qname = str(dns_request.q.qname)

    # Check if the query name exists in the records
    if qname in dns_records:
        record_type, value = dns_records[qname]
        if record_type == 'A':
            dns_response.add_answer(RR(qname, QTYPE.A, rdata=value, ttl=60))
        elif record_type == 'AAAA':
            dns_response.add_answer(RR(qname, QTYPE.AAAA, rdata=value, ttl=60))
        elif record_type == 'CNAME':
            dns_response.add_answer(RR(qname, QTYPE.CNAME, rdata=value, ttl=60))
            # Optionally, add the corresponding A or AAAA record for the CNAME
            if value in dns_records and (dns_records[value][0] == 'A' or dns_records[value][0] == 'AAAA'):
                dns_response.add_answer(RR(value, QTYPE[dns_records[value][0]], rdata=dns_records[value][1], ttl=60))
        elif record_type == 'TXT':
            dns_response.add_answer(RR(qname, QTYPE.TXT, rdata=TXT(value), ttl=60))

    # Send DNS response
    sock.sendto(dns_response.pack(), addr)

In this version, an example AAAA record for ipv6.example.com. with an IPv6 address (2001:0db8:85a3:0000:0000:8a2e:0370:7334) is added to the dns_records dictionary. This dictionary maps domain names to tuples that specify the record type ('A', 'AAAA', 'CNAME', 'TXT') and the record's value (IP address or text).

When constructing the DNS response, the code now checks for 'AAAA' record types alongside the other types and adds the corresponding RR object with QTYPE.AAAA and the IPv6 address as the rdata if a match is found.

This enhanced server is capable of responding to DNS queries for IPv4 (A), IPv6 (AAAA), canonical names (CNAME), and text records (TXT), covering a broader range of DNS record types.

Tags DNS Records DNS Server IPv6 Internet Protocols Networking Programming Tutorial Python Socket Programming Web Development Facebook X
Comments 0
Similar posts
  1. Building a Simple DNS Server in Delphi with TTL Support
    682
  2. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    739
  3. Dynamic DNS Made Easy: Building a Python-Based Solution
    795
  4. Exploring the Depths of Data Transfer: sendfile vs. kTLS
    1,320
  5. Enable/Disable IPv6 on Windows
    1,736
  6. Public DNS (Domain Name Service) based on IPv4, IPv6 widely used
    1,244
  7. How do I determine the client IP type in Python - IPv4 or IPv6
    763
  8. How do I determine the client IP type (IPv4/IPv6) in PHP
    834
  9. Equal Height Blocks in Bootstrap with JavaScript
    711
  10. Mastering Excel Data Importation in PHP
    555
  11. Creating a Pinterest-Style Card Layout with Bootstrap and Masonry
    596
  12. Simple Example to get the total number of records in BigQuery with Python
    666
  13. Learning about Python Multiprocessing Technique
    592
  14. Python script to list files on your Google Drive and download one of them
    941
  15. Method to maximize full CPU performance with Python
    317
  16. Uploading a file to a Google Drive Folder programmatically with Python
    3,307
  17. How to run Python 3.9 on Mac?
    652
  18. Simple Java Code to display Hello, World on the web
    565
  19. Is PyTorch Dead? Deep Learning's Enduring Role Beyond LLMs & Essential Skills
    695
  20. Forecasting with Linear Regression and KNN Regression in Python
    926
  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,158
  23. Harnessing the Power of Random Forest Algorithm in Python
    658
  24. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    633
  25. Python Implementation of Linear Regression
    840
  26. PHP socket programming to get content with post method
    410
  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
    453
  1. Creating mp3 audio file based on the text input with Python
    465
  2. Implementing Text To Speech / Audio with Python3 and pyttsx3
    355
  3. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  4. Python Simplified Assignment Operators
    533
  5. Trackback module used for Python Threading debugging
    843
  6. Python Flask with simple HTML files to server web pages along with API
    927
  7. Python Flask web server tutorial from the scratch
    622
  8. Simple Web Server based in Python
    373
  9. Thread Implementation in Python
    509
  10. A shell script that activates a Python virtual environment and then runs a specific Python script
    743
  11. Using BigQuery in Python
    412
  12. Python Web Programming based on Django from the Scratch
    374
  13. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    188
  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. Uvicorn, Gunicorn: Proving Your Production Prowess
    399
  20. Mastering Random Forest Regression: A Comprehensive Guide with Python Examples
    1,098
  21. Simple Python Clustering Example based on the high school students' score
    340
  22. Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network
    800
  23. Memory Problems with Python Arrays? Discover Dask Array
    324
  24. Mastering Supervised Machine Learning with Python: A Comprehensive Guide
    1,058
  25. 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?
    20,987
  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
    231
  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