brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's ipaddress module checks if an IP is inside a subnet

Python
~/tips/tip-python-ipaddress-in-network

from ipaddress import ip_address, ip_network

Test whether an address belongs to a network range without string tricks.

Checking whether an IP falls in a range with startswith("192.0.2.") works until the range is a /20. The ipaddress module does the maths properly, for IPv4 and IPv6.

from ipaddress import ip_address, ip_network

allowed = ip_network("192.0.2.0/24")
client = ip_address("192.0.2.17")
print(client in allowed)              # True
print(ip_address("127.0.0.1").is_loopback)  # True

net = ip_network("198.51.100.0/29")
print(net.num_addresses, list(net.hosts())[:2])

The objects understand what they are. in checks membership, is_private and is_loopback tell you what kind of address you have, and hosts() lists the usable addresses of a network without the network and broadcast address.

It suits small allowlist checks and input validation. ip_address("300.1.1.1") raises a ValueError, so you get validation for free.

One thing I’d watch out for: ip_network("192.0.2.10/24") raises an error, because host bits are set. Pass strict=False to get the 192.0.2.0/24 network back, or use ip_interface when you really mean an address plus its netmask. And comparing an IPv4 address with an IPv6 network simply returns False, so normalise first if your logs mix both.

Further reading: ipaddress module, An introduction to ipaddress

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link