Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do DNS lookups in Python, including referring to /etc/hosts?

Tags:

python

dns

dnspython will do my DNS lookups very nicely, but it entirely ignores the contents of /etc/hosts.

Is there a python library call which will do the right thing? ie check first in etc/hosts, and only fall back to DNS lookups otherwise?

like image 371
Toby White Avatar asked May 10 '10 18:05

Toby White


People also ask

What command can you use to observe DNS lookup?

Use the command nslookup (this stands for Name Server Lookup) followed by the domain name or IP address you want to trace. Press enter. This command will simply query the Name Service for information about the specified IP address or domain name.

How do I run DNS lookup?

Go to Start and type cmd in the search field to open the command prompt. Alternatively, go to Start > Run > type cmd or command. Type nslookup and hit Enter. The displayed information will be your local DNS server and its IP address.

What sockets function call is used to perform a DNS lookup?

You can use the getaddrinfo() function in the socket module to perform a DNS lookup of a of a domain name, or retrieve information about a domain name or IP address.


1 Answers

I'm not really sure if you want to do DNS lookups yourself or if you just want a host's ip. In case you want the latter,

/!\ socket.gethostbyname is deprecated, prefer socket.getaddrinfo

from man gethostbyname:

The gethostbyname*(), gethostbyaddr*(), [...] functions are obsolete. Applications should use getaddrinfo(3), getnameinfo(3),

import socket print(socket.gethostbyname('localhost')) # result from hosts file print(socket.gethostbyname('google.com')) # your os sends out a dns query 
like image 198
Jochen Ritzel Avatar answered Oct 08 '22 00:10

Jochen Ritzel