Repository navigation
Expand file tree
/
Copy pathnetutils.py
More file actions
60 lines (48 loc) · 1.63 KB
/
Copy pathnetutils.py
File metadata and controls
60 lines (48 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Shared network helpers: internal/external classification and subnets."""
from __future__ import annotations
import ipaddress
from functools import lru_cache
@lru_cache(maxsize=100_000)
def is_internal(ip: str) -> bool:
"""True for private / loopback / link-local / multicast / reserved hosts.
Everything routable on the public internet is 'external'.
"""
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return False
return (
addr.is_private
or addr.is_loopback
or addr.is_link_local
or addr.is_multicast
or addr.is_reserved
or addr.is_unspecified
)
@lru_cache(maxsize=100_000)
def is_noise(ip: str) -> bool:
"""Multicast / broadcast / unspecified addresses — not real hosts.
These (e.g. SSDP 239.255.255.250, 224.0.0.x, 255.255.255.255, 0.0.0.0) are
filtered out of the graph so they don't show up as bogus 'internal hosts'.
"""
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return False
return addr.is_multicast or addr.is_unspecified or ip == "255.255.255.255"
def is_public(ip: str) -> bool:
try:
ipaddress.ip_address(ip)
except ValueError:
return False
return not is_internal(ip)
@lru_cache(maxsize=100_000)
def subnet_of(ip: str) -> str:
"""The /24 (IPv4) or /64 (IPv6) the host belongs to, as a label."""
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return "unknown"
if addr.version == 4:
return str(ipaddress.ip_network(f"{ip}/24", strict=False))
return str(ipaddress.ip_network(f"{ip}/64", strict=False))