Search code examples
pythonsocketsdnssystemdnspython

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.


Solution

  • 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.