5

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?

1

2 Answers 2

3

The most commonly used DNS library for Python seems to be dnspython. After that, see this answer: https://stackoverflow.com/a/6947181/4822566

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

Your solution uses /etc/hosts which should not be done in this particular case. The use case is strange, but this is, what the question is about. The file /etc/hosts most not be used in this case. I want to check that the dns server is reachable and returns a sane result for resolving the name of the current host. DNSSEC or recursive resolution does not matter here. Your question is valid, but it is the valid answer to a slightly different question.
Your solution uses /etc/hosts Not necessarily true, it depends how nsswitch.conf is configured. For your title "Resolve hostname in Python" the above works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.