Search code examples
pythonip-addresshostnamereverse-dns

How to get correct Hostname from reverse DNS lookup using Python?


I need to:

  1. Get the host IP from a client request (DONE)
  2. Perform a reverse DNS lookup (DONE)
  3. Then compare the resulting hostname with the hostname on the Subject Alternative Name (SAN) of the clients SSL cert. (PROBLEM)
  • I need to compare the results of a rdns lookup as "https://knowledge.com" with the SAN shown on the client cert "https://knowledge.com"

If I do a manual reverse lookup on a company using this tool and the domain name, I'm given the IP address:

enter image description here

Here's what I have in Python so far:

import socket

request_ip = xxx.xxx.101.75 # Full IP address actually used

def reverse_dns(request_ip):
    if socket.inet_aton(request_ip):
        try:
            r_dns = socket.gethostbyaddr(request_ip)
        except:
            logging.error('######## Host IP reverse DNS lookup failed. ########')
    else:
        logging.error('######## Host IP is not a valid IP address. ########')
    return r_dns

reverse_dns = reverse_dns(request_ip)

Problem:

  • The list returned from the rdns lookup does not contain the actual hostname but rather a hosting company(?) and IP itself.

('xxx-xxx-101-75.somedata.com', [], ['xxx.xxx.101.75'])

  • How do I get the actual hostname ("https://knowledge.com") as a response from the reverse DNS lookup?

Solution

  • If DNS will give you an IP address for the name knowledge.com, but won't give you the name knowledge.con for that same IP address, then there's no way to get it from DNS.

    A likely reason is that reverse lookup is just not configured. The existence of an A record (name-to-addr) does not require a corresponding PTR record (addr-to-name).

    That's just the way it is.