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.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

17 lines
Python 3.9+
import 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

stdout
['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

  1. Use `socket.gethostbyname_ex(hostname)` for a simpler but less flexible A-record lookup.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.