How to Perform a DNS Lookup for A Records in Python
Resolve a hostname to IPv4 A records using Python's built-in socket.getaddrinfo and return a sorted list of addresses.
Python code
17 linesimport socket
def get_a_records(hostname):
"""Fetch A records (IPv4 addresses) for a given hostname."""
try:
# getaddrinfo with family AF_INET restricts to IPv4 (A records)
infos = socket.getaddrinfo(hostname, None, socket.AF_INET)
# Each info tuple: (family, type, proto, canonname, sockaddr)
a_records = sorted({info[4][0] for info in infos})
return a_records
except socket.gaierror as e:
return f"DNS resolution failed: {e}"
if __name__ == "__main__":
host = "python.org"
result = get_a_records(host)
print(result)
Output
['146.75.78.215', '146.75.78.216']
How it works
This code uses socket.getaddrinfo with the AF_INET family to restrict results to IPv4 addresses (A records). Each returned info tuple contains a sockaddr at index 4, from which we extract the IP as info[4][0]. A set comprehension is used to remove duplicate addresses, and sorted() ensures deterministic output ordering. The try/except block catches socket.gaierror, which is raised for invalid hostnames or network errors, returning a readable error message instead of crashing.
Common mistakes
- Forgetting to pass `AF_INET`, which returns IPv6 (AAAA) records too and mixes address formats.
- Accessing `info[4][0]` incorrectly when the info tuple structure isn't understood.
- Not handling `socket.gaierror` for invalid hostnames or network failures.
- Assuming the output order is stable without sorting.
Variations
- Use `socket.gethostbyname_ex(hostname)` for a simpler but less flexible A-record lookup.
- Switch to `socket.AF_INET6` to fetch IPv6 AAAA records for modern dual-stack networks.
Real-world use cases
- Periodic health checks that verify a domain still resolves before routing traffic to it.
- A diagnostic script that audits which IP addresses a consumer-facing hostname advertises.
- Automating internal service discovery by resolving a known hostname and updating firewall rules.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.