File: example1.rst

package info (click to toggle)
ldns 1.8.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,864 kB
  • sloc: ansic: 46,986; python: 7,675; sh: 4,229; perl: 2,186; makefile: 1,231; xml: 518
file content (68 lines) | stat: -rw-r--r-- 2,099 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
Resolving the MX records
==============================

This basic example shows how to create a resolver which asks for MX records which contain the information about mail servers.

::

	#!/usr/bin/python
	#
	# MX is a small program that prints out the mx records for a particular domain
	#
	import ldns
	
	resolver = ldns.ldns_resolver.new_frm_file("/etc/resolv.conf")

	dname = ldns.ldns_dname("nic.cz")
	
	pkt = resolver.query(dname, ldns.LDNS_RR_TYPE_MX, ldns.LDNS_RR_CLASS_IN, ldns.LDNS_RD)
	if (pkt):
		mx = pkt.rr_list_by_type(ldns.LDNS_RR_TYPE_MX, ldns.LDNS_SECTION_ANSWER)
		if (mx):
			mx.sort()
			print mx

Resolving step by step
------------------------

First of all we import :mod:`ldns` extension module which make LDNS functions and classes accessible::

	import ldns

If importing fails, it means that Python cannot find the module or ldns library.

Then we create the resolver by :meth:`ldns.ldns_resolver.new_frm_file` constructor ::

	resolver = ldns.ldns_resolver.new_frm_file("/etc/resolv.conf")

and domain name variable dname::

	dname = ldns.ldns_dname("nic.cz")

To create a resolver you may also use::

	resolver = ldns.ldns_resolver.new_frm_file(None)

which behaves in the same manner as the command above.

In the third step we tell the resolver to query for our domain, type MX, of class IN::
	
	pkt = resolver.query(dname, ldns.LDNS_RR_TYPE_MX, ldns.LDNS_RR_CLASS_IN, ldns.LDNS_RD)

The function should return a packet if everything goes well and this packet will contain resource records we asked for. 
Note that there exists a simpler way. Instead of using a dname variable, we can use a string which will be automatically converted.
::

	pkt = resolver.query("fit.vutbr.cz", ldns.LDNS_RR_TYPE_MX, ldns.LDNS_RR_CLASS_IN, ldns.LDNS_RD)

Now, we test whether the resolver returns a packet and then get all RRs of type MX from the answer packet and store them in list mx::

	if (pkt):
		mx = pkt.rr_list_by_type(ldns.LDNS_RR_TYPE_MX, ldns.LDNS_SECTION_ANSWER)

If this list is not empty, we sort and print the content to stdout::

	if (mx):
		mx.sort()
		print mx