Sounds like you don't want to resolve dns yourself (this might be the wrong nomenclature) dnspython appears to be a standalone dns client that will understandably ignore your operating system because its bypassing the operating system's utillities.
We can look at a shell utility named getent
to understand how the (debian 11 alike) operating system resolves dns for programs, this is likely the standard for all *nix like systems that use a socket implementation.
see man getent
's "hosts" section, which mentions the use of getaddrinfo
, which we can see as man getaddrinfo
and to use it in python, we have to extract some info from the data structures
.
import socket
def get_ipv4_by_hostname(hostname):
# see `man getent` `/ hosts `
# see `man getaddrinfo`
return list(
i # raw socket structure
[4] # internet protocol info
[0] # address
for i in
socket.getaddrinfo(
hostname,
0 # port, required
)
if i[0] is socket.AddressFamily.AF_INET # ipv4
# ignore duplicate addresses with other socket types
and i[1] is socket.SocketKind.SOCK_RAW
)
print(get_ipv4_by_hostname('localhost'))
print(get_ipv4_by_hostname('google.com'))