blob: 5e0ff3ed1b68bd2be2b5c8382c83c761714fc470 [file] [log] [blame]
Nick Coghlan53c92002012-05-27 01:53:33 +10001.. _ipaddress-howto:
2
Nick Coghlan9680bdb2012-06-17 17:24:10 +10003***************************************
Eli Bendersky948af232012-10-07 07:23:50 -07004An introduction to the ipaddress module
Nick Coghlan9680bdb2012-06-17 17:24:10 +10005***************************************
Nick Coghlan53c92002012-05-27 01:53:33 +10006
7:author: Peter Moody
Nick Coghlan9680bdb2012-06-17 17:24:10 +10008:author: Nick Coghlan
Nick Coghlan53c92002012-05-27 01:53:33 +10009
Nick Coghlan9680bdb2012-06-17 17:24:10 +100010.. topic:: Overview
Nick Coghlan53c92002012-05-27 01:53:33 +100011
Nick Coghlanccd712a2012-07-07 22:53:46 +100012 This document aims to provide a gentle introduction to the
13 :mod:`ipaddress` module. It is aimed primarily at users that aren't
14 already familiar with IP networking terminology, but may also be useful
15 to network engineers wanting an overview of how :mod:`ipaddress`
16 represents IP network addressing concepts.
Nick Coghlan53c92002012-05-27 01:53:33 +100017
18
19Creating Address/Network/Interface objects
20==========================================
21
Eli Benderskydfd72bb2012-07-31 17:25:33 +030022Since :mod:`ipaddress` is a module for inspecting and manipulating IP addresses,
Nick Coghlan53c92002012-05-27 01:53:33 +100023the first thing you'll want to do is create some objects. You can use
24:mod:`ipaddress` to create objects from strings and integers.
25
26
27A Note on IP Versions
28---------------------
29
30For readers that aren't particularly familiar with IP addressing, it's
31important to know that the Internet Protocol is currently in the process
32of moving from version 4 of the protocol to version 6. This transition is
33occurring largely because version 4 of the protocol doesn't provide enough
34addresses to handle the needs of the whole world, especially given the
35increasing number of devices with direct connections to the internet.
36
37Explaining the details of the differences between the two versions of the
38protocol is beyond the scope of this introduction, but readers need to at
39least be aware that these two versions exist, and it will sometimes be
40necessary to force the use of one version or the other.
41
42
43IP Host Addresses
44-----------------
45
46Addresses, often referred to as "host addresses" are the most basic unit
47when working with IP addressing. The simplest way to create addresses is
Nick Coghlanccd712a2012-07-07 22:53:46 +100048to use the :func:`ipaddress.ip_address` factory function, which automatically
49determines whether to create an IPv4 or IPv6 address based on the passed in
Eli Bendersky948af232012-10-07 07:23:50 -070050value:
51
52.. testsetup::
53 >>> import ipaddress
54
55::
Nick Coghlan53c92002012-05-27 01:53:33 +100056
57 >>> ipaddress.ip_address('192.0.2.1')
58 IPv4Address('192.0.2.1')
59 >>> ipaddress.ip_address('2001:DB8::1')
60 IPv6Address('2001:db8::1')
61
62Addresses can also be created directly from integers. Values that will
63fit within 32 bits are assumed to be IPv4 addresses::
64
65 >>> ipaddress.ip_address(3221225985)
66 IPv4Address('192.0.2.1')
67 >>> ipaddress.ip_address(42540766411282592856903984951653826561)
68 IPv6Address('2001:db8::1')
69
70To force the use of IPv4 or IPv6 addresses, the relevant classes can be
71invoked directly. This is particularly useful to force creation of IPv6
72addresses for small integers::
73
74 >>> ipaddress.ip_address(1)
75 IPv4Address('0.0.0.1')
76 >>> ipaddress.IPv4Address(1)
77 IPv4Address('0.0.0.1')
78 >>> ipaddress.IPv6Address(1)
79 IPv6Address('::1')
80
81
82Defining Networks
83-----------------
84
85Host addresses are usually grouped together into IP networks, so
86:mod:`ipaddress` provides a way to create, inspect and manipulate network
87definitions. IP network objects are constructed from strings that define the
88range of host addresses that are part of that network. The simplest form
89for that information is a "network address/network prefix" pair, where the
90prefix defines the number of leading bits that are compared to determine
91whether or not an address is part of the network and the network address
92defines the expected value of those bits.
93
94As for addresses, a factory function is provided that determines the correct
95IP version automatically::
96
97 >>> ipaddress.ip_network('192.0.2.0/24')
98 IPv4Network('192.0.2.0/24')
99 >>> ipaddress.ip_network('2001:db8::0/96')
100 IPv6Network('2001:db8::/96')
101
102Network objects cannot have any host bits set. The practical effect of this
103is that ``192.0.2.1/24`` does not describe a network. Such definitions are
104referred to as interface objects since the ip-on-a-network notation is
105commonly used to describe network interfaces of a computer on a given network
106and are described further in the next section.
107
108By default, attempting to create a network object with host bits set will
109result in :exc:`ValueError` being raised. To request that the
110additional bits instead be coerced to zero, the flag ``strict=False`` can
111be passed to the constructor::
112
113 >>> ipaddress.ip_network('192.0.2.1/24')
114 Traceback (most recent call last):
115 ...
116 ValueError: 192.0.2.1/24 has host bits set
117 >>> ipaddress.ip_network('192.0.2.1/24', strict=False)
118 IPv4Network('192.0.2.0/24')
119
120While the string form offers significantly more flexibility, networks can
121also be defined with integers, just like host addresses. In this case, the
122network is considered to contain only the single address identified by the
123integer, so the network prefix includes the entire network address::
124
125 >>> ipaddress.ip_network(3221225984)
126 IPv4Network('192.0.2.0/32')
Nick Coghlan9680bdb2012-06-17 17:24:10 +1000127 >>> ipaddress.ip_network(42540766411282592856903984951653826560)
Nick Coghlan53c92002012-05-27 01:53:33 +1000128 IPv6Network('2001:db8::/128')
129
Nick Coghlanccd712a2012-07-07 22:53:46 +1000130As with addresses, creation of a particular kind of network can be forced
131by calling the class constructor directly instead of using the factory
132function.
Nick Coghlan53c92002012-05-27 01:53:33 +1000133
134
135Host Interfaces
136---------------
137
138As mentioned just above, if you need to describe an address on a particular
139network, neither the address nor the network classes are sufficient.
Nick Coghlanccd712a2012-07-07 22:53:46 +1000140Notation like ``192.0.2.1/24`` is commonly used by network engineers and the
Nick Coghlan53c92002012-05-27 01:53:33 +1000141people who write tools for firewalls and routers as shorthand for "the host
142``192.0.2.1`` on the network ``192.0.2.0/24``", Accordingly, :mod:`ipaddress`
143provides a set of hybrid classes that associate an address with a particular
144network. The interface for creation is identical to that for defining network
145objects, except that the address portion isn't constrained to being a network
146address.
147
148 >>> ipaddress.ip_interface('192.0.2.1/24')
149 IPv4Interface('192.0.2.1/24')
Eli Bendersky948af232012-10-07 07:23:50 -0700150 >>> ipaddress.ip_interface('2001:db8::1/96')
Nick Coghlan53c92002012-05-27 01:53:33 +1000151 IPv6Interface('2001:db8::1/96')
152
153Integer inputs are accepted (as with networks), and use of a particular IP
154version can be forced by calling the relevant constructor directly.
155
156
157Inspecting Address/Network/Interface Objects
158============================================
159
160You've gone to the trouble of creating an IPv(4|6)(Address|Network|Interface)
161object, so you probably want to get information about it. :mod:`ipaddress`
162tries to make doing this easy and intuitive.
163
164Extracting the IP version::
165
166 >>> addr4 = ipaddress.ip_address('192.0.2.1')
167 >>> addr6 = ipaddress.ip_address('2001:db8::1')
168 >>> addr6.version
169 6
170 >>> addr4.version
171 4
172
173Obtaining the network from an interface::
174
175 >>> host4 = ipaddress.ip_interface('192.0.2.1/24')
176 >>> host4.network
177 IPv4Network('192.0.2.0/24')
178 >>> host6 = ipaddress.ip_interface('2001:db8::1/96')
179 >>> host6.network
180 IPv6Network('2001:db8::/96')
181
182Finding out how many individual addresses are in a network::
183
184 >>> net4 = ipaddress.ip_network('192.0.2.0/24')
Eli Bendersky948af232012-10-07 07:23:50 -0700185 >>> net4.num_addresses
Nick Coghlan53c92002012-05-27 01:53:33 +1000186 256
187 >>> net6 = ipaddress.ip_network('2001:db8::0/96')
Eli Bendersky948af232012-10-07 07:23:50 -0700188 >>> net6.num_addresses
Nick Coghlan53c92002012-05-27 01:53:33 +1000189 4294967296
190
Eli Benderskydfd72bb2012-07-31 17:25:33 +0300191Iterating through the "usable" addresses on a network::
Nick Coghlan53c92002012-05-27 01:53:33 +1000192
193 >>> net4 = ipaddress.ip_network('192.0.2.0/24')
Eli Benderskydfd72bb2012-07-31 17:25:33 +0300194 >>> for x in net4.hosts():
Eli Bendersky948af232012-10-07 07:23:50 -0700195 ... print(x) # doctest: +ELLIPSIS
Nick Coghlan53c92002012-05-27 01:53:33 +1000196 192.0.2.1
197 192.0.2.2
198 192.0.2.3
199 192.0.2.4
Eli Bendersky948af232012-10-07 07:23:50 -0700200 ...
Nick Coghlan53c92002012-05-27 01:53:33 +1000201 192.0.2.252
202 192.0.2.253
203 192.0.2.254
204
205
206Obtaining the netmask (i.e. set bits corresponding to the network prefix) or
207the hostmask (any bits that are not part of the netmask):
208
209 >>> net4 = ipaddress.ip_network('192.0.2.0/24')
210 >>> net4.netmask
211 IPv4Address('255.255.255.0')
212 >>> net4.hostmask
213 IPv4Address('0.0.0.255')
214 >>> net6 = ipaddress.ip_network('2001:db8::0/96')
215 >>> net6.netmask
216 IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff::')
217 >>> net6.hostmask
218 IPv6Address('::ffff:ffff')
219
220
221Exploding or compressing the address::
222
Nick Coghlan53c92002012-05-27 01:53:33 +1000223 >>> addr6.exploded
Eli Bendersky948af232012-10-07 07:23:50 -0700224 '2001:0db8:0000:0000:0000:0000:0000:0001'
Nick Coghlanccd712a2012-07-07 22:53:46 +1000225 >>> addr6.compressed
Eli Bendersky948af232012-10-07 07:23:50 -0700226 '2001:db8::1'
Nick Coghlanccd712a2012-07-07 22:53:46 +1000227 >>> net6.exploded
228 '2001:0db8:0000:0000:0000:0000:0000:0000/96'
229 >>> net6.compressed
230 '2001:db8::/96'
231
232While IPv4 doesn't support explosion or compression, the associated objects
233still provide the relevant properties so that version neutral code can
234easily ensure the most concise or most verbose form is used for IPv6
235addresses while still correctly handling IPv4 addresses.
Nick Coghlan53c92002012-05-27 01:53:33 +1000236
237
238Networks as lists of Addresses
239==============================
240
241It's sometimes useful to treat networks as lists. This means it is possible
242to index them like this::
243
244 >>> net4[1]
245 IPv4Address('192.0.2.1')
246 >>> net4[-1]
247 IPv4Address('192.0.2.255')
248 >>> net6[1]
Eli Bendersky948af232012-10-07 07:23:50 -0700249 IPv6Address('2001:db8::1')
Nick Coghlan53c92002012-05-27 01:53:33 +1000250 >>> net6[-1]
Eli Bendersky948af232012-10-07 07:23:50 -0700251 IPv6Address('2001:db8::ffff:ffff')
Nick Coghlan53c92002012-05-27 01:53:33 +1000252
253
254It also means that network objects lend themselves to using the list
255membership test syntax like this::
256
257 if address in network:
258 # do something
259
260Containment testing is done efficiently based on the network prefix::
261
262 >>> addr4 = ipaddress.ip_address('192.0.2.1')
263 >>> addr4 in ipaddress.ip_network('192.0.2.0/24')
264 True
265 >>> addr4 in ipaddress.ip_network('192.0.3.0/24')
266 False
267
268
269Comparisons
270===========
271
272:mod:`ipaddress` provides some simple, hopefully intuitive ways to compare
273objects, where it makes sense::
274
275 >>> ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2')
276 True
277
278A :exc:`TypeError` exception is raised if you try to compare objects of
279different versions or different types.
280
281
282Using IP Addresses with other modules
283=====================================
284
285Other modules that use IP addresses (such as :mod:`socket`) usually won't
286accept objects from this module directly. Instead, they must be coerced to
287an integer or string that the other module will accept::
288
289 >>> addr4 = ipaddress.ip_address('192.0.2.1')
290 >>> str(addr4)
291 '192.0.2.1'
292 >>> int(addr4)
293 3221225985
294
295
Nick Coghlanb582ecc2012-07-07 22:15:22 +1000296Getting more detail when instance creation fails
297================================================
Nick Coghlan53c92002012-05-27 01:53:33 +1000298
Nick Coghlan9680bdb2012-06-17 17:24:10 +1000299When creating address/network/interface objects using the version-agnostic
Nick Coghlanb582ecc2012-07-07 22:15:22 +1000300factory functions, any errors will be reported as :exc:`ValueError` with
301a generic error message that simply says the passed in value was not
Eli Benderskydfd72bb2012-07-31 17:25:33 +0300302recognized as an object of that type. The lack of a specific error is
Nick Coghlanb582ecc2012-07-07 22:15:22 +1000303because it's necessary to know whether the value is *supposed* to be IPv4
304or IPv6 in order to provide more detail on why it has been rejected.
Nick Coghlan9680bdb2012-06-17 17:24:10 +1000305
Nick Coghlanb582ecc2012-07-07 22:15:22 +1000306To support use cases where it is useful to have access to this additional
307detail, the individual class constructors actually raise the
308:exc:`ValueError` subclasses :exc:`ipaddress.AddressValueError` and
309:exc:`ipaddress.NetmaskValueError` to indicate exactly which part of
310the definition failed to parse correctly.
Nick Coghlan53c92002012-05-27 01:53:33 +1000311
Nick Coghlanb582ecc2012-07-07 22:15:22 +1000312The error messages are significantly more detailed when using the
313class constructors directly. For example::
314
315 >>> ipaddress.ip_address("192.168.0.256")
316 Traceback (most recent call last):
317 ...
318 ValueError: '192.168.0.256' does not appear to be an IPv4 or IPv6 address
319 >>> ipaddress.IPv4Address("192.168.0.256")
320 Traceback (most recent call last):
321 ...
322 ipaddress.AddressValueError: Octet 256 (> 255) not permitted in '192.168.0.256'
323
324 >>> ipaddress.ip_network("192.168.0.1/64")
325 Traceback (most recent call last):
326 ...
327 ValueError: '192.168.0.1/64' does not appear to be an IPv4 or IPv6 network
328 >>> ipaddress.IPv4Network("192.168.0.1/64")
329 Traceback (most recent call last):
330 ...
331 ipaddress.NetmaskValueError: '64' is not a valid netmask
332
333However, both of the module specific exceptions have :exc:`ValueError` as their
Nick Coghlan53c92002012-05-27 01:53:33 +1000334parent class, so if you're not concerned with the particular type of error,
Nick Coghlan9680bdb2012-06-17 17:24:10 +1000335you can still write code like the following::
Nick Coghlan53c92002012-05-27 01:53:33 +1000336
337 try:
Nick Coghlanb582ecc2012-07-07 22:15:22 +1000338 network = ipaddress.IPv4Network(address)
Nick Coghlan53c92002012-05-27 01:53:33 +1000339 except ValueError:
Nick Coghlanb582ecc2012-07-07 22:15:22 +1000340 print('address/netmask is invalid for IPv4:', address)
341