Python Glossary Русский

Python 3.3+ipaddressfunction

ipaddress.ip_network()

factory functions

Creates an IPv4Network or IPv6Network from notation like '192.168.1.0/24'; by default it strictly checks that the address is the start of the network.

Syntax

ipaddress.ip_network(address, strict=True)

The main trap is strict=True by default: '192.168.1.5/24' fails with ValueError 'has host bits set' because host bits are set in what should be a network address. If the input is a host address with a mask, pass strict=False, which zeroes the host bits, or use ip_interface(), which keeps both the address and the network. The mask can be a prefix or a full mask: '/24' and '/255.255.255.0' give the same network.

Examples

import ipaddress
print(ipaddress.ip_network('192.168.1.5/24', strict=False))  # → 192.168.1.0/24
print(ipaddress.ip_network('192.168.1.0/255.255.255.0'))  # → 192.168.1.0/24
ipaddress.ip_network('192.168.1.5/24')  # → ValueError: 192.168.1.5/24 has host bits set

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy