The fourth chapter of the Python Network programming basics Domain Name System

Source: Internet
Author: User

The Domain Name System (DNS) is a distributed database that is primarily used to convert host names to IP addresses. DNS and related systems exist for the following two reasons:

    • They can make it easier to remember names, such as www.baidu.com.
    • They allow the server to change the IP address, but the same name is used.
As an example, let's take a look at the query www.baidu.com first, your program communicates with the local name server specified by the operating system configuration file. This server is aRecursive name servers, it receives the request and passes it in the proper way, and it will do a lot of work for you. The first thing a recursive server does is ask for a. com domain. The latter has a built-in list of top-level domains that can distribute information about the world's top-level domains, such as. com this loop repeats multiple times until the final query reaches the name server of the www.baidu.com service.        This server knows the IP address in question and returns it.   Using the operating system query service the operating system itself brings some functionality for DNS lookups (often referred to as the Resolver library). The most basic query that executes a basic query is a forward query that looks up an IP address based on a host name. For example, you want to download a Web page from www.baidu.com.      First you need to find the IP address.      In Python, the function you will use is Socket.getaddrinfo (), and sockaddr is actually the address of the remote machine.     The value here is printed in the form of a tuple.   It is also possible to get all the entries through Getaddrinfo (). Import Sys,socket



result = Socket.getaddrinfo (Sys.argv[1],none)

Counter = 0

For item in Result:
Print "%-2d:%s"% (Counter,item[4])
Counter + = 1


Note: The same entry may not be displayed more than once on your machine. On some platforms, such as Windows getaddrinfo (), only one protocol is supported by default. Even on platforms that support multiple protocols, there is only one result if some protocols are not configured. To limit the results so that each entry is displayed only once, you need to set the socket for the protocol parameter. Sock_stream for the family parameter set 0, let IT support all family here's a better version of the previous example: Import Sys,socket


result = Socket.getaddrinfo (sys.argv[1],none,0,socket. SOCK_STREAM)


Counter = 0

For item in Result:
Print "%-2d:%s"% (Counter,item[4])
Counter + = 1




This time, you will see that each entry is displayed only once. To perform a reverse query reverse lookup base There is an important question you need to understand, that is, for an IP address, there is a possibility that there is no reverse mapping. In fact, many IP addresses do not have a corresponding domain name at all.  Therefore, you need to ensure that socket.herror () is captured and processed for each reverse lookup behavior. Import Sys,socket



Try
# Perform The Lookup
result = Socket.gethostbyaddr (sys.argv[1])


print "Primary hostname:"
Print "" + result[0]



Print "\naddresses:"
For item in RESULT[2]:
Print "" + Item

Except Socket.herror, E:
print "couldn ' t look up name:", E



For reverse queries, authorization is based on the IP address. Import Sys,socket

def GETIPADDRS (hostname):
result = Socket.getaddrinfo (hostname,none,0,socket. SOCK_STREAM)
return [x[4][0] for x in result]


def gethostname (ipaddr):
Return socket.gethostbyaddr (IPADDR) [0]




Try

hostname = GetHostName (sys.argv[1])

Ipaddrs = Getipaddrs (hostname)


Except Socket.herror,e:
Print "No host names available for%s;this is normal."% sys.argv[1]
Sys.exit (0)

Except Socket.gaierror,e:
print "Got hostname%s,but It could not being forward-resolved:%s"% (HOSTNAME,STR (e))
Sys.exit (1)



If not sys.argv[1] in Ipaddrs:
Print "Got hostname%s. But on forward lookup, "% hostname
Print "Original IP%s did not appear in IP Address list."% sys.argv[1]
#print "\ n%s"% (hostname)
Sys.exit (1)



Print "Validated hostname:%s"% (hostname)


Get Environmental Information Import Sys,socket

def GETIPADDRS (hostname):
result = Socket.getaddrinfo (hostname,none,0,socket. SOCK_STREAM)
return [x[4][0] for x in result]




hostname = Socket.gethostname ()

Print "Host name:", hostname





Print "fully-qualified name:", SOCKET.GETFQDN (hostname)

Try
Print "IP address:", GETIPADDRS (hostname)

Except Socket.gaierror,e:
print "couldn ' t not get IP addresses:%s", (e)

Use Pydns for advanced query DNS Records when you execute any type of query, either through Pydns or through the query functionality of the operating system described earlier, you get multiple types of Records from a single name server. The following is a list of most records you will encounter: the simple Pydns Query Pydns library provides the Python module DNS.    First you should call Dns.discovernameservers () in your application, which allows you to locate the name server in your system, which is the Registry (registry) on your UNIX system and is/etc/resolv.conf     All Pydns queries are sent to these servers. After initializing the name server, the next step is to create a request object, which is implemented by calling Dns.request ().   This object can be used to issue any DNS query requests. Import Sys,dns

query = Sys,dns


query = sys.argv[1]

Dns. Discovernameservers ()


Reqobj = DNS. Request ()



Answerobj = reqobj.req (name = Query,qtype = DNS. Type.any)

If not Len (answerobj.answers):
Print "Not FOUND."

For item in Answerobj.answers:
Print "%-5s%s"% (item[' typename '],item[' data ') it's useless!!!! Querying for Special name servers

The fourth chapter of the Python Network programming basics Domain Name System

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.