Python Glossary Русский

Python 3.3+ipaddressfunction

ipaddress.ip_address()

factory functions

Creates an IPv4Address or IPv6Address from a string, an integer or bytes, picking the protocol version by itself.

Syntax

ipaddress.ip_address(address)

A bad string raises a plain ValueError, not AddressValueError: the factory does not know which version you meant, so except AddressValueError around it never fires. An integer is taken as the address number: ip_address(1) is 0.0.0.1, and anything from 2**32 up becomes IPv6. Surrounding spaces and leading zeros in octets ('010.0.0.1') are rejected, so strip() user input first.

Examples

import ipaddress
print(repr(ipaddress.ip_address('192.168.0.1')))  # → IPv4Address('192.168.0.1')
print(repr(ipaddress.ip_address('::1')))  # → IPv6Address('::1')
print(repr(ipaddress.ip_address(1)))  # → IPv4Address('0.0.0.1') — число, а не строка
import ipaddress
def is_ip(text):
    try:
        ipaddress.ip_address(text.strip())
        return True
    except ValueError:  # AddressValueError здесь не прилетит
        return False
print(is_ip(' 10.0.0.1 '), is_ip('192.168.0.256'), is_ip('010.0.0.1'))  # → True False False

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy