ipaddress 模組介紹¶
- 作者:
Peter Moody
- 作者:
Nick Coghlan
總攬
這份文件旨在為ipaddress
模組提供一個初步介紹。文件主要針對那些不熟悉 IP 網路術語的使用者,但對想要了解ipaddress
模組如何表示 IP 網址概念的網路工程師也可能有用。
建立 Address/Network/Interface 物件¶
Sinceipaddress
is a module for inspecting and manipulating IP addresses,the first thing you'll want to do is create some objects. You can useipaddress
to create objects from strings and integers.
A Note on IP Versions¶
For readers that aren't particularly familiar with IP addressing, it'simportant to know that the Internet Protocol (IP) is currently in the processof moving from version 4 of the protocol to version 6. This transition isoccurring largely because version 4 of the protocol doesn't provide enoughaddresses to handle the needs of the whole world, especially given theincreasing number of devices with direct connections to the internet.
Explaining the details of the differences between the two versions of theprotocol is beyond the scope of this introduction, but readers need to atleast be aware that these two versions exist, and it will sometimes benecessary to force the use of one version or the other.
IP Host Addresses¶
Addresses, often referred to as "host addresses" are the most basic unitwhen working with IP addressing. The simplest way to create addresses isto use theipaddress.ip_address()
factory function, which automaticallydetermines whether to create an IPv4 or IPv6 address based on the passed invalue:
>>>ipaddress.ip_address('192.0.2.1')IPv4Address('192.0.2.1')>>>ipaddress.ip_address('2001:DB8::1')IPv6Address('2001:db8::1')
Addresses can also be created directly from integers. Values that willfit within 32 bits are assumed to be IPv4 addresses:
>>>ipaddress.ip_address(3221225985)IPv4Address('192.0.2.1')>>>ipaddress.ip_address(42540766411282592856903984951653826561)IPv6Address('2001:db8::1')
To force the use of IPv4 or IPv6 addresses, the relevant classes can beinvoked directly. This is particularly useful to force creation of IPv6addresses for small integers:
>>>ipaddress.ip_address(1)IPv4Address('0.0.0.1')>>>ipaddress.IPv4Address(1)IPv4Address('0.0.0.1')>>>ipaddress.IPv6Address(1)IPv6Address('::1')
定義網路¶
Host addresses are usually grouped together into IP networks, soipaddress
provides a way to create, inspect and manipulate networkdefinitions. IP network objects are constructed from strings that define therange of host addresses that are part of that network. The simplest formfor that information is a "network address/network prefix" pair, where theprefix defines the number of leading bits that are compared to determinewhether or not an address is part of the network and the network addressdefines the expected value of those bits.
As for addresses, a factory function is provided that determines the correctIP version automatically:
>>>ipaddress.ip_network('192.0.2.0/24')IPv4Network('192.0.2.0/24')>>>ipaddress.ip_network('2001:db8::0/96')IPv6Network('2001:db8::/96')
Network objects cannot have any host bits set. The practical effect of thisis that192.0.2.1/24
does not describe a network. Such definitions arereferred to as interface objects since the ip-on-a-network notation iscommonly used to describe network interfaces of a computer on a given networkand are described further in the next section.
By default, attempting to create a network object with host bits set willresult inValueError
being raised. To request that theadditional bits instead be coerced to zero, the flagstrict=False
canbe passed to the constructor:
>>>ipaddress.ip_network('192.0.2.1/24')Traceback (most recent call last):...ValueError:192.0.2.1/24 has host bits set>>>ipaddress.ip_network('192.0.2.1/24',strict=False)IPv4Network('192.0.2.0/24')
While the string form offers significantly more flexibility, networks canalso be defined with integers, just like host addresses. In this case, thenetwork is considered to contain only the single address identified by theinteger, so the network prefix includes the entire network address:
>>>ipaddress.ip_network(3221225984)IPv4Network('192.0.2.0/32')>>>ipaddress.ip_network(42540766411282592856903984951653826560)IPv6Network('2001:db8::/128')
As with addresses, creation of a particular kind of network can be forcedby calling the class constructor directly instead of using the factoryfunction.
Host Interfaces¶
As mentioned just above, if you need to describe an address on a particularnetwork, neither the address nor the network classes are sufficient.Notation like192.0.2.1/24
is commonly used by network engineers and thepeople who write tools for firewalls and routers as shorthand for "the host192.0.2.1
on the network192.0.2.0/24
", Accordingly,ipaddress
provides a set of hybrid classes that associate an address with a particularnetwork. The interface for creation is identical to that for defining networkobjects, except that the address portion isn't constrained to being a networkaddress.
>>>ipaddress.ip_interface('192.0.2.1/24')IPv4Interface('192.0.2.1/24')>>>ipaddress.ip_interface('2001:db8::1/96')IPv6Interface('2001:db8::1/96')
Integer inputs are accepted (as with networks), and use of a particular IPversion can be forced by calling the relevant constructor directly.
檢視 Address/Network/Interface 物件¶
You've gone to the trouble of creating an IPv(4|6)(Address|Network|Interface)object, so you probably want to get information about it.ipaddress
tries to make doing this easy and intuitive.
Extracting the IP version:
>>>addr4=ipaddress.ip_address('192.0.2.1')>>>addr6=ipaddress.ip_address('2001:db8::1')>>>addr6.version6>>>addr4.version4
Obtaining the network from an interface:
>>>host4=ipaddress.ip_interface('192.0.2.1/24')>>>host4.networkIPv4Network('192.0.2.0/24')>>>host6=ipaddress.ip_interface('2001:db8::1/96')>>>host6.networkIPv6Network('2001:db8::/96')
Finding out how many individual addresses are in a network:
>>>net4=ipaddress.ip_network('192.0.2.0/24')>>>net4.num_addresses256>>>net6=ipaddress.ip_network('2001:db8::0/96')>>>net6.num_addresses4294967296
Iterating through the "usable" addresses on a network:
>>>net4=ipaddress.ip_network('192.0.2.0/24')>>>forxinnet4.hosts():...print(x)192.0.2.1192.0.2.2192.0.2.3192.0.2.4...192.0.2.252192.0.2.253192.0.2.254
Obtaining the netmask (i.e. set bits corresponding to the network prefix) orthe hostmask (any bits that are not part of the netmask):
>>>net4=ipaddress.ip_network('192.0.2.0/24')>>>net4.netmaskIPv4Address('255.255.255.0')>>>net4.hostmaskIPv4Address('0.0.0.255')>>>net6=ipaddress.ip_network('2001:db8::0/96')>>>net6.netmaskIPv6Address('ffff:ffff:ffff:ffff:ffff:ffff::')>>>net6.hostmaskIPv6Address('::ffff:ffff')
Exploding or compressing the address:
>>>addr6.exploded'2001:0db8:0000:0000:0000:0000:0000:0001'>>>addr6.compressed'2001:db8::1'>>>net6.exploded'2001:0db8:0000:0000:0000:0000:0000:0000/96'>>>net6.compressed'2001:db8::/96'
While IPv4 doesn't support explosion or compression, the associated objectsstill provide the relevant properties so that version neutral code caneasily ensure the most concise or most verbose form is used for IPv6addresses while still correctly handling IPv4 addresses.
Networks as lists of Addresses¶
It's sometimes useful to treat networks as lists. This means it is possibleto index them like this:
>>>net4[1]IPv4Address('192.0.2.1')>>>net4[-1]IPv4Address('192.0.2.255')>>>net6[1]IPv6Address('2001:db8::1')>>>net6[-1]IPv6Address('2001:db8::ffff:ffff')
It also means that network objects lend themselves to using the listmembership test syntax like this:
ifaddressinnetwork:# 做某些事情
Containment testing is done efficiently based on the network prefix:
>>>addr4=ipaddress.ip_address('192.0.2.1')>>>addr4inipaddress.ip_network('192.0.2.0/24')True>>>addr4inipaddress.ip_network('192.0.3.0/24')False
比較¶
ipaddress
provides some simple, hopefully intuitive ways to compareobjects, where it makes sense:
>>>ipaddress.ip_address('192.0.2.1')<ipaddress.ip_address('192.0.2.2')True
ATypeError
exception is raised if you try to compare objects ofdifferent versions or different types.
Using IP Addresses with other modules¶
Other modules that use IP addresses (such assocket
) usually won'taccept objects from this module directly. Instead, they must be coerced toan integer or string that the other module will accept:
>>>addr4=ipaddress.ip_address('192.0.2.1')>>>str(addr4)'192.0.2.1'>>>int(addr4)3221225985
Getting more detail when instance creation fails¶
When creating address/network/interface objects using the version-agnosticfactory functions, any errors will be reported asValueError
witha generic error message that simply says the passed in value was notrecognized as an object of that type. The lack of a specific error isbecause it's necessary to know whether the value issupposed to be IPv4or IPv6 in order to provide more detail on why it has been rejected.
To support use cases where it is useful to have access to this additionaldetail, the individual class constructors actually raise theValueError
subclassesipaddress.AddressValueError
andipaddress.NetmaskValueError
to indicate exactly which part ofthe definition failed to parse correctly.
The error messages are significantly more detailed when using theclass constructors directly. For example:
>>>ipaddress.ip_address("192.168.0.256")Traceback (most recent call last):...ValueError:'192.168.0.256' does not appear to be an IPv4 or IPv6 address>>>ipaddress.IPv4Address("192.168.0.256")Traceback (most recent call last):...ipaddress.AddressValueError:Octet 256 (> 255) not permitted in '192.168.0.256'>>>ipaddress.ip_network("192.168.0.1/64")Traceback (most recent call last):...ValueError:'192.168.0.1/64' does not appear to be an IPv4 or IPv6 network>>>ipaddress.IPv4Network("192.168.0.1/64")Traceback (most recent call last):...ipaddress.NetmaskValueError:'64' is not a valid netmask
However, both of the module specific exceptions haveValueError
as theirparent class, so if you're not concerned with the particular type of error,you can still write code like the following:
try:network=ipaddress.IPv4Network(address)exceptValueError:print('address/netmask is invalid for IPv4:',address)