Jonathan Allen Grant
Jonathan Allen Grant

Reputation: 3648

How can I get the hostname, aliases, ip address, and canonical name of a device (without asking a library to read /etc/hosts) using python?

I want to get these fields about a device given an identifier:

hostname, aliases, ip address, & canonical name

I can get these by using socket:

socket.gethostbyaddr('machine-name')

However, every socket call opens the hosts file (/etc/hosts) and reads it in. I want to skip this step.

Either I want socket to only open the hosts file once (and save the data), or I want socket to skip looking in the hosts file and do a DNS lookup (and I will read the hosts file myself).

I tried to do this with dnspython's resolver, but I can't figure out how to parse the returned result for my wanted fields.

Upvotes: 4

Views: 2870

Answers (2)

Jonathan Allen Grant
Jonathan Allen Grant

Reputation: 3648

I ended up achieving this with pycares. It allowed me to resolve 100,000+ dns queries in under 18 seconds.

For the hosts file, I parsed it myself.

Upvotes: 0

Patrick Mevzek
Patrick Mevzek

Reputation: 12515

If you need absolutely and uniquely a DNS query, then do a DNS query!

Otherwise gethostbyaddr asks the OS which use any sources configured.

See this from the manual:

The domain name queries carried out by gethostbyname() and gethostbyaddr() rely on the Name Service Switch (nsswitch.conf(5)) configured sources or a local name server (named(8)). The default action is to query the Name Service Switch (nsswitch.conf(5)) configured sources, failing that, a local name server (named(8)).

So you can have a look at the manual for nsswitch.conf to learn more about this.

If you control the host, you can edit the file and put in it:

hosts: dns

and then you will be sure that gethostbyaddr queries only the DNS.

But if you application is supposed to be executed on various hosts, and you need to do DNS queries, then just do DNS queries with the appropriate library.

If you do a search here on "dnspython" you will find many examples on how to use it, for example: returning 'A' DNS record in dnspython

Upvotes: 1

Related Questions