On this page
  1. ipaddress
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Guarding Against SSRF (Blocking Private / Loopback / Link-Local IPs)
  7. 2. Subnetting & Iterating Usable Hosts
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

ipaddress

Prev: io | Up: stdlib_module | Next: itertools
Rel: email, json, mailbox, mimetypes, base64
Ref: docs.python.org — ipaddress
Tags: #public #python3 #stdlib


Import

import ipaddress

Overview

Type-safe IPv4 and IPv6 address, subnet/CIDR network, and host-interface objects (ip_address, ip_network, ip_interface). Reach for ipaddress for CIDR membership checks, SSRF allow/blocklists (is_private, is_loopback, is_global), and subnet splitting instead of error-prone string splitting.

Quick Start

import ipaddress

addr = ipaddress.ip_address("192.168.1.42")
net = ipaddress.ip_network("192.168.1.0/24")

assert addr in net
assert addr.is_private and not addr.is_global
assert net.num_addresses == 256

Implementation Walkthrough

import ipaddress

def is_public_ip(raw: str) -> bool:
    try:
        ip = ipaddress.ip_address(raw)
    except ValueError:
        return False
    return ip.is_global and not (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast)

assert is_public_ip("93.184.216.34")
assert not is_public_ip("127.0.0.1")
assert not is_public_ip("169.254.169.254")

2. Subnetting & Iterating Usable Hosts

import ipaddress

net = ipaddress.ip_network("10.0.0.0/24")
halves = list(net.subnets(new_prefix=25))
assert [str(s) for s in halves] == ["10.0.0.0/25", "10.0.0.128/25"]

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes