How to Build a DNS Lookup Tool in Python
Building a DNS lookup tool is a great way to understand how domain names resolve to IP addresses. Using Python’s built-in socket module (and optionally dnspython for advanced queries), you can create a command-line utility in under 50 lines of code. This tutorial walks you through the essential steps.
1. Basic Setup with Socket
The socket.gethostbyname() function returns the IPv4 address for a given domain. Create a simple script that takes a domain as input:
- Import the
socketmodule - Use
sys.argvto capture command-line arguments - Call
socket.gethostbyname(domain)inside a try/except block - Print the result or an error message
This gives you a minimal DNS lookup tool for A records.
2. Adding More Record Types with dnspython
For MX, NS, CNAME, and TXT records, install dnspython (pip install dnspython). Key steps:
- Use
dns.resolver.resolve(domain, record_type) - Iterate over the response and print each answer
- Wrap calls in try/except for common errors like NXDOMAIN or no answer
This gives you a versatile tool that can query any DNS record type.
3. Making It User-Friendly
Enhance your tool with a simple menu or argument parser (argparse):
- Allow the user to specify record type via
-tflag (default: A) - Add a
--verboseoption to show query times - Include help text with
-h
Example usage: python dns_lookup.py example.com -t MX
Conclusion
With just a few lines of Python, you can build a practical DNS lookup tool. Start with socket for basic A records, then extend with dnspython for advanced queries. This project teaches networking fundamentals and gives you a useful utility for troubleshooting domain resolutions.