File: get-ip.py

package info (click to toggle)
python-getdns 1.0.0~b1-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 448 kB
  • sloc: ansic: 3,538; python: 607; makefile: 130
file content (70 lines) | stat: -rwxr-xr-x 2,011 bytes parent folder | download | duplicates (4)
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
69
70
#!/usr/bin/env python
#

"""
get-ip.py: resolve given DNS names into IP addresses. The -s switch
constains answers to only ones secured by DNSSEC. The -4 switch only
returns IPv4 addresses, the -6 switch only IPv6 addresses.

An example run:

    $ get-ip.py -s www.huque.com www.google.com
    www.huque.com: IPv4  50.116.63.23
    www.huque.com: IPv6  2600:3c03:e000:81::a
    www.google.com: No DNSSEC secured responses found

"""

import getdns, sys, getopt

def usage():
    print("""\
Usage: get-ip.py [-s] [-4|-6] <domain1> <domain2> ...

    -s: only return DNSSEC secured answers
    -4: only return IPv4 address answers
    -6: only return IPv6 address answers

-4 and -6 are mutually exclusive. If both are specified, IPv6 wins.
""")
    sys.exit(1)

try:
    (options, args) = getopt.getopt(sys.argv[1:], 's46')
except getopt.GetoptError:
    usage()
else:
    if not args:
        usage()

extensions = { "return_both_v4_and_v6" : getdns.EXTENSION_TRUE }
desired_addr_type = None

for (opt, optval) in options:
    if opt == "-s":
        extensions["dnssec_return_only_secure"] = getdns.EXTENSION_TRUE
    elif opt == "-4":
        desired_addr_type = "IPv4"
    elif opt == "-6":
        desired_addr_type = "IPv6"

ctx = getdns.Context()

for hostname in args:
    try:
        results = ctx.address(name=hostname, extensions=extensions)
    except getdns.error as e:
        print(str(e))
        break
    status = results.status
    if status == getdns.RESPSTATUS_GOOD:
        for addr in results.just_address_answers:
            addr_type = addr['address_type']
            addr_data = addr['address_data']
            if (desired_addr_type == None) or (addr_type == desired_addr_type):
                print("{0}: {1}  {2}".format(hostname, addr_type, addr_data))
    elif status == getdns.RESPSTATUS_NO_SECURE_ANSWERS:
        print("{0}: No DNSSEC secured responses found".format(hostname))
    else:
        print("{0}: getdns.address() returned error: {1}".format(hostname, status))