revy
revy

Reputation: 4707

python get primary domain name from ip

I need to get primary domain name from ip. I have some doubts about how functions like gethostbyaddr and getfqdn work.

In the following example I'm going to reverse ip a random domain and then try to get the domain name back:

import socket

domain = 'heroku.com'

# get ip from domain
ip = socket.gethostbyname(domain)
print('ip =', ip)

# get domain from ip
print(socket.gethostbyaddr(ip))
print(socket.getfqdn(ip))

# OUTPUT
# ip = 50.19.85.154
# ('ec2-50-19-85-154.compute-1.amazonaws.com', ['154.85.19.50.in-addr.arpa'], ['50.19.85.154'])
# ec2-50-19-85-154.compute-1.amazonaws.com

It seems both gethostbyaddr and getfqdn are returning the public DNS of one of the load balanced ec2 on AWS. My question is why they don't return the domain heroku.com which is probably the domain registered on Route53?

Another example with google.com:

import socket

domain = 'google.com'

# get ip from domain
ip = socket.gethostbyname(domain)
print('ip =', ip)

# get domain from ip
print(socket.gethostbyaddr(ip))
print(socket.getfqdn(ip))

# OUTPUT
# ip = 216.58.208.174
# ('mil07s10-in-f14.1e100.net', ['174.208.58.216.in-addr.arpa', 'lhr25s09-in-f14.1e100.net', 'lhr25s09-in-f174.1e100.net'], ['216.58.208.174'])
# mil07s10-in-f14.1e100.net

Here again it seems they are returning the public DNS of some machine on GCP. How can I get the real primary domain name from an ip address (heroku.com and google.com in these examples)?

Upvotes: 0

Views: 1534

Answers (1)

m0hithreddy
m0hithreddy

Reputation: 1829

When we do a DNS lookup of a hostname, in the most of the cases we are returned with the CNAME. We take that CNAME, and further resolve it to get an IP. But multiple CNAME's in the (n-1)th stage can be mapped to the CNAME in the (n)th stage. Therefore getting back the CNAME from the CNAME of the later stages is a not a trivial task.

Another Possible Way

Well, now the discussion is moving away from the DNS, but I hope it helps you. Every router or node in the internet is mapped to a Autonomous System, and there are some organizations or sites which maintain this mapping database. So by having the IP, we can contact one such database to get its Autonomous System Number (ASN) and the organization to which the node belongs to. whois.cymru.com:43 is one such site. You can use simple network client like nc to query its database. Below I attached the screenshot of one such query.

enter image description here

Upvotes: 1

Related Questions