Resolving a hostname to an IP address helps scripts connect to the correct remote service, record where a DNS name currently points, and confirm a network target before opening a socket.
The socket module passes hostname lookups to the operating system resolver. socket.gethostbyname() returns one IPv4 address string, while socket.gethostbyname_ex() returns the primary hostname, alias list, and all IPv4 addresses currently returned for the same name.
Resolver results follow local DNS answers, search domains, and hosts-file entries, so the same hostname can return different addresses across systems or between runs. Current Python documentation still describes both functions as IPv4-only interfaces, so workflows that must handle IPv6 or explicit address-family selection should use socket.getaddrinfo() instead. The hostname and address samples below stay masked with documentation-only values so the return shape remains realistic without publishing a live resolver target.
Related: Get a hostname from an IP address
Related: Extract a hostname from a URL
$ python3 Python 3.14.3 >>>
>>> import socket
>>> socket.gethostbyname("api.edge.example.net")
'198.51.100.24'
A hostname can be a short local name or a fully qualified domain name such as api.edge.example.net.
The returned IPv4 address can differ between runs when DNS rotates across several records.
>>> socket.gethostbyname_ex("api.edge.example.net")
('api.edge.example.net', [], ['198.51.100.24', '198.51.100.25'])
The returned tuple is (hostname, aliaslist, ipaddrlist).
Use socket.getaddrinfo() instead when the workflow needs IPv6 results or explicit address-family selection.
#!/usr/bin/env python3 import socket import sys if len(sys.argv) != 2: raise SystemExit(f"Usage: {sys.argv[0]} <hostname>") hostname = sys.argv[1] try: primary_name, aliases, addresses = socket.gethostbyname_ex(hostname) except socket.gaierror as exc: raise SystemExit(f"Lookup failed for {hostname}: {exc}") print(f"Input hostname: {hostname}") print(f"Canonical hostname: {primary_name}") if aliases: print("Aliases:") for alias in aliases: print(f" {alias}") print("IPv4 addresses:") for address in addresses: print(f" {address}")
The script uses socket.gethostbyname_ex() so one lookup can expose the primary name and every current IPv4 answer.
$ python3 hostname-to-ip.py api.edge.example.net Input hostname: api.edge.example.net Canonical hostname: api.edge.example.net IPv4 addresses: 198.51.100.24 198.51.100.25
Address order and membership can change when the hostname is served through multiple records or a CDN.
$ python3 hostname-to-ip.py api-edge-01.invalid Lookup failed for api-edge-01.invalid: [Errno 8] nodename nor servname provided, or not known
The exact resolver error text can vary by operating system, but socket.gaierror remains the failure condition to catch.