If you’ve ever wondered how to convert a domain name like google.com into an IP address or fetch all its DNS records using Python, you’ve come to the right place.
Python DNS lookup is a fundamental task in network programming, system administration, and even cybersecurity.
In this guide, we’ll cover everything from basic socket methods to advanced dnspython queries, including reverse DNS lookup, error handling, and bulk DNS queries. By the end, you’ll have all the tools needed for real-world Python DNS applications.
What is DNS Lookup?
DNS, or Domain Name System, is essentially the phonebook of the internet. When you type a domain into your browser, DNS translates it into an IP address so your device can connect.
A Python DNS lookup is the process of programmatically querying DNS servers to retrieve information about domains. This can include:
- A and AAAA records (IPv4 and IPv6)
- MX records (mail servers)
- NS records (name servers)
- TXT records (SPF, DKIM, and other metadata)
It’s essential for tasks like verifying server configurations, troubleshooting network issues, or automating system monitoring.
How DNS Lookup Works in Python?

Python offers multiple ways to perform DNS lookups. You can use built-in modules like socket or third-party libraries like dnspython. The key is to choose the right method for your task:
- socket: Quick and simple for single IP lookups
- dnspython: Advanced, supports all record types and bulk queries
- getaddrinfo: Handles IPv4 and IPv6 queries efficiently
PowerShell DNS lookup generally follow a client-server model: your Python script sends a query to a DNS server, which returns the requested record type.
Python DNS Lookup Using socket (Beginner Method)
For many small projects, the built-in socket module is sufficient.
Using socket.gethostbyname()
“ import socket
ip_address = socket.gethostbyname(‘google.com’)
print(f’The IP address of google.com is {ip_address}’) “
- Simple and fast
- Only supports A records
- Ideal for single-domain lookups
Using socket.getaddrinfo()
“ info = socket.getaddrinfo(‘google.com’, 80)
for result in info:
print(result[4][0]) “
- Supports IPv4 and IPv6
- Returns more detailed information
- Useful when you need port-specific info
Note: Python DNS lookup with socket is limited for advanced record types but great for lightweight scripts and educational purposes.
Advanced DNS Lookup Using dnspython (Recommended)

For robust projects, dnspython is the go-to library. It supports all DNS record types and can query specific servers, handle bulk lookups, and even perform reverse lookups.
Install dnspython
“ pip install dnspython “
A Record Lookup
“ import dns.resolver
result = dns.resolver.resolve(‘google.com’, ‘A’)
for ip in result:
print(ip.to_text()) “
- Fetches all IPv4 addresses
- Works with Python 3
- Handles multiple records automatically
MX Record Lookup
“ result = dns.resolver.resolve(‘gmail.com’, ‘MX’)
for mx in result:
print(mx.exchange, mx.preference) “
- Retrieves mail server info
- Essential for email validation scripts
TXT Record Lookup
“ result = dns.resolver.resolve(‘google.com’, ‘TXT’)
for txt in result:
print(txt.to_text()) “
- Useful for SPF, DKIM, DMARC records
- Frequently used in security checks
NS Record Lookup
“ result = dns.resolver.resolve(‘google.com’, ‘NS’)
for ns in result:
print(ns.to_text()) “
- Shows authoritative name servers
CNAME and PTR Records
“ # CNAME Example
result = dns.resolver.resolve(‘www.example.com’, ‘CNAME’)
for cname in result:
print(cname.to_text())
# PTR (Reverse) Example
result = dns.resolver.resolve(‘8.8.8.8’, ‘PTR’)
for ptr in result:
print(ptr.to_text()) ”
- CNAME: Canonical names
- PTR: Reverse DNS for IP → Domain
Reverse DNS Lookup in Python
Reverse DNS is crucial when you need to verify the domain associated with an IP address.
“ import socket
host = socket.gethostbyaddr(‘8.8.8.8’)
print(host) “
- Returns a tuple with hostname, alias list, and IP addresses
- Use Python DNS reverse lookup in security scripts, email verification, or logging
Python DNS Lookup Errors & Fixes
Even in Python, DNS lookups can fail. Handling errors ensures your scripts don’t crash unexpectedly.
Common Errors
- dns.resolver.NXDOMAIN: Domain does not exist
- dns.resolver.Timeout: DNS server timeout
- dns.resolver.NoAnswer: No record found
- socket.gaierror: Invalid hostname
How to Fix?
try:
“ result = dns.resolver.resolve(‘nonexistentdomain.com’, ‘A’)
except dns.resolver.NXDOMAIN:
print(“Domain does not exist”)
except dns.resolver.Timeout:
print(“DNS request timed out”) “
- Always implement try/except blocks
- Increase lifetime parameter for slow servers
- Validate domain names before queries
Real-World Use Cases of Python DNS Lookup

- Website IP Verification: Ensure your domain points correctly to the server
- Email Server Validation: Check MX records for automated email systems
- Network Debugging: Identify DNS misconfigurations
- Security Analysis: Map domains and detect spoofing
- Automation Scripts: Bulk DNS lookup in Python for monitoring
Bulk DNS lookup Python scripts can save hours in enterprise-level tasks.
Best Practices for DNS Lookup in Python
- Always handle exceptions
- Avoid hardcoding DNS servers
- Use dnspython for production-grade scripts
- Cache results when querying large lists
- Consider async solutions for high-volume lookups
Conclusion
Python DNS lookup is a versatile tool for developers, sysadmins, and cybersecurity professionals.
From basic socket lookups to advanced dnspython queries, understanding DNS in Python allows you to automate tasks, debug networks, and secure infrastructure.
Implement error handling, comparison, and real-world use cases to create scripts that are reliable and production-ready.
By following this guide, you now have everything to perform Python DNS lookup, reverse lookups, bulk queries, and all record types efficiently.
FAQs
What is the best way to do DNS lookup in Python?
For most tasks, dnspython is recommended. For simple A record lookups, socket.gethostbyname() is sufficient.
Can Python get MX records?
Yes, using “ dns.resolver.resolve(‘domain.com’, ‘MX’)”. This fetches all mail server records.
Is dnspython better than socket?
Yes, dnspython supports all record types, bulk queries, and advanced error handling. Socket is limited to basic lookups.
How to do reverse DNS lookup in Python?
Use “ socket.gethostbyaddr(‘IP_ADDRESS’) “ or “ dns.resolver.resolve(‘IP’, ‘PTR’) “ for reverse lookups.
Why DNS lookup fails sometimes?
Common reasons include non-existent domains (NXDOMAIN), timeouts, misconfigured servers, or incorrect record type queries.