1 min read

Python Ipaddress Module

The ipaddress module provides the capabilities to create, manipulate and operate on IPv4 and IPv6 addresses and networks.

Importing the Module

import ipaddress

Address Objects

The ip_address() factory function automatically determines whether to create an IPv4 or IPv6 address based on the passed value.

import ipaddress

ipv4 = ipaddress.ip_address('192.168.0.1')
print(ipv4)          # 192.168.0.1
print(ipv4.version)  # 4

ipv6 = ipaddress.ip_address('2001:db8::1')
print(ipv6)          # 2001:db8::1
print(ipv6.version)  # 6

Properties

You can check various properties of an IP address.

print(ipv4.is_private)  # True
print(ipv4.is_global)   # False

Network Objects

The ip_network() function creates a network object. By default, it raises a ValueError if host bits are set. Use strict=False to ignore this.

import ipaddress

net = ipaddress.ip_network('192.168.0.0/24')
print(net) # 192.168.0.0/24

# Iterating over hosts
for x in net.hosts():
    print(x)
    break # Print only the first one
# Output: 192.168.0.1

Network Membership

You can check if an address belongs to a network.

addr = ipaddress.ip_address('192.168.0.5')
print(addr in net) # True

Interface Objects

Interface objects are hybrid objects that hold both an IP address and a network mask.

import ipaddress

interface = ipaddress.ip_interface('192.168.0.1/24')
print(interface.ip)      # 192.168.0.1
print(interface.network) # 192.168.0.0/24

programming/python/python