bhylu.com

Advertisements

Cybersecurity IP Addresses and Subnets

Check whether an address belongs to an explicitly defined network.

How it works

An IP address identifies a network interface in a routing context. A subnet prefix describes a range of addresses. Membership is an exact bit-prefix calculation, not a text starts-with check. Private address space is useful inside networks but does not prove that a device is trusted; compromised internal devices remain possible. Network notation with host bits set may be rejected by strict parsing; make that validation error visible rather than silently broadening an allowlist.

Run the code

Save the complete source as ip-addresses.py in a separate learning folder, then run python ip-addresses.py. The reviewed runtime is Python 3.12.14 with the standard library; no third-party packages are required. These are local examples, not browser playground programs. Apache, MySQL and PHP are not needed.

Download the complete source

Local lab setup

Example

ip-addresses.py

import ipaddress
network = ipaddress.ip_network("10.42.8.0/24")
assert ipaddress.ip_address("10.42.8.19") in network
assert ipaddress.ip_address("10.42.9.19") not in network
print("inside: True; outside: False")

Expected result

inside: True; outside: False

The /24 prefix fixes the first 24 address bits. The two assertions differ in the third octet, so one address falls outside this example network. ipaddress also parses IPv6; production allowlists must deliberately support or reject that family and handle invalid input.

Technical reference: Python ipaddress. Check the guidance for your actual platform and deployment.