I want to resolve a hostname with Python.
But, I don't want that /etc/hosts
gets used.
My usecase is checking if DNS is working.
How can I force name resolution via DNS in Python?
The most commonly used DNS library for Python seems to be dnspython. After that, see this answer: https://stackoverflow.com/a/6947181/4822566
You do not need a specific Python library to resolve hostnames in general, as this is a core libc feature and hence a core feature of any programming language. This was written at the time your question was not specific to using the DNS, in which case using a DNS library is of course the only solution. The below text remains correct for generic resolution of names from Python.
See socket.getaddrinfo at https://docs.python.org/3.8/library/socket.html#socket.getaddrinfo whose description is:
Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service.
and
The function returns a list of 5-tuples with the following structure:
(family, type, proto, canonname, sockaddr)
and their example:
>>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP)
[(<AddressFamily.AF_INET6: 10>, <SocketType.SOCK_STREAM: 1>, 6, '',
('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
(<AddressFamily.AF_INET: 2>, <SocketType.SOCK_STREAM: 1>, 6, '',
('93.184.216.34', 80))]
This may or may not use the DNS as the libc will use /etc/resolv.conf
, /etc/gai.conf
, /etc/nsswitch.conf
and /etc/hosts
(typically on an Unix system) to decide how to resolve names and where.
As for
My usecase is checking if DNS is working.
This is too vague. How do you define "DNS is working"? You mean your specifc recursive nameserver replies? Or some distant one? Or is DNSSEC activated? Or are answers spoofed or not? Or are some specific domain name correctly configured and responding to DNS queries? etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With