Classify addresses against supplied networks
Use IPv4 and IPv6 network membership instead of string-prefix guesses.
A network is a range of addresses
192.0.2.0/24 describes a network prefix. A string beginning with 192.0.2 is not necessarily a valid member: 192.0.20.8 is outside it. ipaddress.ip_address() and ip_network() turn text into values that understand address boundaries.
Use strict network parsing so a configuration such as 192.0.2.5/24 is rejected for having host bits set. Quietly changing that value into a larger network could widen an investigation rule without the analyst noticing.
Internal is a policy label
For this task, internal means membership in one of the supplied networks. External means a valid address outside all of them. It does not mean publicly routable, suspicious, or safe. Documentation networks are intentionally used throughout the course, so relying on is_private would answer a different question.
IPv6 has several equivalent textual forms. Converting an address object back to a string gives a canonical spelling for joins and reports. Keep the original input alongside that value so a reviewer can see what changed.
An invalid observation becomes an invalid row. An invalid configured network raises an error before any observations are classified. This distinction separates bad evidence from a broken rule. No addresses are contacted, and no DNS resolution is involved.
from ipaddress import ip_address, ip_network
print(ip_address("192.0.2.8") in ip_network("192.0.2.0/24"))
print(str(ip_address("2001:0db8:0:0::5")))
Put it into practice.
Define classify_addresses(addresses, networks). Parse configured networks strictly; invalid configurations raise ValueError. For each input string return input (unchanged), address (canonical string or None), and scope: internal if in a supplied same-version network, external otherwise, invalid if unparseable. Strip surrounding whitespace for parsing. Preserve input order. Include both IPv4 and IPv6; do not use is_private as the policy.
See an explained solution
from ipaddress import ip_address, ip_network
def classify_addresses(addresses, networks):
prefixes = [ip_network(value, strict=True) for value in networks]
rows = []
for value in addresses:
try:
address = ip_address(value.strip())
except ValueError:
rows.append({"input": value, "address": None, "scope": "invalid"})
continue
internal = any(address.version == net.version and address in net for net in prefixes)
rows.append({"input": value, "address": str(address), "scope": "internal" if internal else "external"})
return rows
Address objects provide real range membership and canonical output. The report uses the supplied policy rather than conflating internal addresses with special-purpose address categories.