Python implementation of DNS forward query the reverse query example

  • 2020-04-02 13:36:15
  • OfStack

1.DNS query process:

Take www.baidu.com as an example

(1) the computer sends a request to the local domain name server to resolve www.baidu.com
(2) after the local domain name server received the request, the first query local cache, if found directly returned the query results, if there is no record, the local domain name server sent www.baidu.com request to the root domain name server
(3) after the root domain server receives the request, return the server IP address of the.com domain to the local domain server
(4) the local domain name server connects to the.com server and requests to resolve the domain name www.baidu.com. The.com server returns the IP address of the baidu.com server to the local DNS server
(5) the local DNS server sends a resolution domain name request to the baidu.com server, and the baidu.com server returns the IP address of www.baidu.com to the local DNS server
(6) the local DNS server returns the IP address of www.baidu.com to the computer.

2. Correspondence between domain name and IP address:

A domain name can correspond to more than one IP address, but at the same time, a domain name can only have one IP address, an IP address can correspond to more than one domain name.

3. The query DNS

Python can implement forward and reverse DNS queries. The following is Forward query code:


#!/usr/bin/env python
import sys,socket
result=socket.getaddrinfo(sys,argv[1],None)
print result[0][4]

Because a domain name can have more than one IP address, the results of two runs of the program may be different.

Running procedure:

./test.py www.baidu.com

The result is:
( ' 111.13.100.91',80)

Reverse query:


#!/usr/bin/env python
import sys,socket
try:
 result=socket.gethostbyaddr(sys.argv[1])
 print "hostname is "+result[0]
except socket.herror,e:
 print "can't look up"

To run the program

./test2  127.0.0.1

The result is:
hostname is localhost


Related articles: