Py3DNS - Python 3 DNS library

4.0.2 · active · verified Fri Apr 17

Py3DNS is a Python 3 library for making DNS queries and parsing responses. It provides a flexible API for various record types (A, AAAA, MX, NS, SOA, etc.) and is a port of the older `pydns` library, specifically adapted for Python 3. The current version is 4.0.2, with updates primarily focusing on Python compatibility, bug fixes, and feature enhancements like `asyncio` support.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to perform basic A and MX record DNS queries using Py3DNS. It includes name server discovery and a fallback to public DNS if discovery fails, making the example robust for various environments.

import DNS
import os

# Configure name servers, typically from system settings
# For testing, you can explicitly set them or rely on system discovery
# Example using Google's DNS for demonstration if system discovery fails or for specific testing
# DNS.defaults['server'] = ['8.8.8.8', '8.8.4.4']

# Discover name servers from /etc/resolv.conf or common system locations
DNS.DiscoverNameServers()

# Ensure name servers were found or set
if not DNS.defaults.get('server'):
    print("Warning: No DNS name servers discovered. Queries might fail.")
    print("Attempting to use public DNS servers as fallback.")
    DNS.defaults['server'] = ['8.8.8.8', '8.8.4.4'] # Fallback to Google DNS

# Make an A record query for google.com
try:
    req = DNS.Request(name='google.com', qtype='A')
    response = req.req()

    print(f"DNS Query for google.com (A records):\n")
    if response.answers:
        for answer in response.answers:
            print(f"  Name: {answer.name}, Type: {answer.qtype}, Data: {answer.data}, TTL: {answer.ttl}")
    else:
        print("  No A records found for google.com.")

    # Example: MX record query
    req_mx = DNS.Request(name='example.com', qtype='MX')
    response_mx = req_mx.req()
    print(f"\nDNS Query for example.com (MX records):\n")
    if response_mx.answers:
        for answer in response_mx.answers:
            print(f"  Name: {answer.name}, Type: {answer.qtype}, Priority: {answer.data[0]}, Exchange: {answer.data[1]}")
    else:
        print("  No MX records found for example.com.")

except DNS.DNSError as e:
    print(f"DNS Error: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →