w3resource

Python: Get the domain name using PTR DNS records from a given IP address

Python Basic - 1: Exercise-141 with Solution

Write a Python program to get the domain name using PTR DNS records from a given IP address.

What is a DNS PTR record?

The Domain Name System, or DNS, correlates domain names with IP addresses. A DNS pointer record (PTR for short) provides the domain name associated with an IP address. A DNS PTR record is exactly the opposite of the 'A' record, which provides the IP address associated with a domain name.

DNS PTR records are used in reverse DNS lookups. When a user attempts to reach a domain name in their browser, a DNS lookup occurs, matching the domain name to the IP address. A reverse DNS lookup is the opposite of this process: it is a query that starts with the IP address and looks up the domain name. Source: cloudflare.com

Sample Solution-1:

Python Code:

def get_domain_name(ip_address):
  import socket
  result=socket.gethostbyaddr(ip_address)
  return list(result)[0]
print("Domain name using PTR DNS:")
print(get_domain_name("8.8.8.8"))
print(get_domain_name("13.251.106.90"))
print(get_domain_name("8.8.4.4"))
print(get_domain_name("23.23.212.126"))

Sample Output:

Domain name using PTR DNS:
dns.google
ec2-13-251-106-90.ap-southeast-1.compute.amazonaws.com
dns.google
ec2-23-23-212-126.compute-1.amazonaws.com

Flowchart:

Flowchart: Python - Get the domain name using PTR DNS records from a given IP address.

Sample Solution-2:

Python Code:

def get_domain_name(ip_address):
  import socket
  return socket.getfqdn(ip_address)
print("Domain name using PTR DNS:")
print(get_domain_name("8.8.8.8"))
print(get_domain_name("13.251.106.90"))
print(get_domain_name("8.8.4.4"))
print(get_domain_name("23.23.212.126"))

Sample Output:

Domain name using PTR DNS:
dns.google
ec2-13-251-106-90.ap-southeast-1.compute.amazonaws.com
dns.google
ec2-23-23-212-126.compute-1.amazonaws.com

Flowchart:

Flowchart: Python - Get the the domain name using PTR DNS records from a given IP address.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to convert all items in a given list to float values.
Next: Write a Python program to check if every consecutive sequence of zeroes is followed by a consecutive sequence of ones of same length in a given string. Return True/False.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.