ipaddress Filters Access By Network
Gate client addresses with the ipaddress module: parse and reject malformed hosts, then test CIDR allowlist membership instead of string prefix compares.
Code
import ipaddress
# 允许访问的网段:内网两段 + 一个具体的外部合作方地址
ALLOWLIST = [
ipaddress.ip_network("10.0.0.0/8"),
ipaddress.ip_network("192.168.1.0/24"),
ipaddress.ip_network("203.0.113.7/32"),
]
def is_allowed(client: str) -> bool:
try:
addr = ipaddress.ip_address(client) # 非法字符串抛 ValueError
except ValueError:
return False
# 字符串前缀比较会误放行,成员判断才是准确的网段语义
return any(addr in net for net in ALLOWLIST)
for client in ["10.1.2.3", "192.168.1.44", "203.0.113.7", "8.8.8.8", "10.0.0.999"]:
print(f"{client:>10} -> {is_allowed(client)}")
# IPv4 网段永远不包含 v6 地址:协议族不同
v6 = ipaddress.ip_address("::ffff:10.1.2.3")
print("v6 in v4 net:", any(v6 in net for net in ALLOWLIST))Output
Captured from a sandboxed run of this snippet in the build pipeline.
10.1.2.3 -> True
192.168.1.44 -> True
203.0.113.7 -> True
8.8.8.8 -> False
10.0.0.999 -> False
v6 in v4 net: FalseWhat the code does
ipaddress Filters Access By Network is built around the function is_allowed.
The one repetition in this snippet is the loop for client in ["10.1.2.3", "192.168.1.44", "203.0.113.7", "8.8.8.8", "10.0.0.999"].
Points of care
- External dependency:
ipaddress— install it before running the snippet.
Using it
The main signature reads def is_allowed(client: str) -> bool
Running the file prints labeled results such as v6 in v4 net: — each operation’s effect is visible in the output.
is_allowed is what another module would consume; nothing else here is load-bearing for callers.
Key statements
def is_allowed(client: str) -> bool:
try:
addr = ipaddress.ip_address(client) # 非法字符串抛 ValueError
except ValueError:
return False
# 字符串前缀比较会误放行,成员判断才是准确的网段语义
return any(addr in net for net in ALLOWLIST)
Interactive Tools for This Topic
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Every import resolves inside the standard library — `ipaddress`. The file defines `is_allowed` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.