1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 """Generic Internet address helper functions."""
19
20 import socket
21
22 import dns.ipv4
23 import dns.ipv6
24
25 from ._compat import maybe_ord
26
27
28
29 AF_INET = socket.AF_INET
30
31
32
33
34
35 try:
36 AF_INET6 = socket.AF_INET6
37 except AttributeError:
38 AF_INET6 = 9999
39
40
42 """Convert the textual form of a network address into its binary form.
43
44 *family* is an ``int``, the address family.
45
46 *text* is a ``text``, the textual address.
47
48 Raises ``NotImplementedError`` if the address family specified is not
49 implemented.
50
51 Returns a ``binary``.
52 """
53
54 if family == AF_INET:
55 return dns.ipv4.inet_aton(text)
56 elif family == AF_INET6:
57 return dns.ipv6.inet_aton(text)
58 else:
59 raise NotImplementedError
60
61
63 """Convert the binary form of a network address into its textual form.
64
65 *family* is an ``int``, the address family.
66
67 *address* is a ``binary``, the network address in binary form.
68
69 Raises ``NotImplementedError`` if the address family specified is not
70 implemented.
71
72 Returns a ``text``.
73 """
74
75 if family == AF_INET:
76 return dns.ipv4.inet_ntoa(address)
77 elif family == AF_INET6:
78 return dns.ipv6.inet_ntoa(address)
79 else:
80 raise NotImplementedError
81
82
84 """Determine the address family of a textual-form network address.
85
86 *text*, a ``text``, the textual address.
87
88 Raises ``ValueError`` if the address family cannot be determined
89 from the input.
90
91 Returns an ``int``.
92 """
93
94 try:
95 dns.ipv4.inet_aton(text)
96 return AF_INET
97 except Exception:
98 try:
99 dns.ipv6.inet_aton(text)
100 return AF_INET6
101 except:
102 raise ValueError
103
104
106 """Is the textual-form network address a multicast address?
107
108 *text*, a ``text``, the textual address.
109
110 Raises ``ValueError`` if the address family cannot be determined
111 from the input.
112
113 Returns a ``bool``.
114 """
115
116 try:
117 first = maybe_ord(dns.ipv4.inet_aton(text)[0])
118 return first >= 224 and first <= 239
119 except Exception:
120 try:
121 first = maybe_ord(dns.ipv6.inet_aton(text)[0])
122 return first == 255
123 except Exception:
124 raise ValueError
125