network-validators 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ .pytest_cache/
5
+ build/
6
+ dist/
7
+ out/
8
+ .DS_Store
9
+ .vscode/
10
+ .idea/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 icmp-type0
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.5
2
+ Name: network-validators
3
+ Version: 0.1.0
4
+ Summary: Validators for IP addresses, subnets, ranges, hostnames, ports and MAC addresses, with stable error codes.
5
+ Project-URL: Homepage, https://github.com/icmp-type0/network-validators-py
6
+ Project-URL: Specification, https://github.com/icmp-type0/network-validators-py/blob/main/spec/SPEC.md
7
+ Project-URL: Issues, https://github.com/icmp-type0/network-validators-py/issues
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: cidr,fqdn,hostname,ip,ipv4,ipv6,mac,port,subnet,validation
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: System :: Networking
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest>=8; extra == 'test'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # network-validators
28
+
29
+ Validators for network-related input: IP addresses, subnets, IP ranges, hostnames, ports and MAC addresses. Each check returns a stable error code, not a message, so you write the messages your users see.
30
+
31
+ - No dependencies. Python 3.11+.
32
+ - Strict about common traps: IPv4 leading zeros (CVE-2021-29921), non-ASCII digits, surrounding whitespace, IPv6 zone IDs.
33
+ - Behaves the same as the [TypeScript package](https://www.npmjs.com/package/network-validators). Both follow one [specification](https://github.com/icmp-type0/network-validators-py/blob/main/spec/SPEC.md) and run the same test cases.
34
+
35
+ > Status: 0.1. Before 1.0, a minor version (0.2, 0.3, …) may include breaking changes. Every change is listed in the [changelog](https://github.com/icmp-type0/network-validators-py/blob/main/CHANGELOG.md).
36
+
37
+ ## Install
38
+
39
+ ```sh
40
+ pip install network-validators
41
+ ```
42
+
43
+ ## Usage
44
+
45
+ Every validator has two forms: `validate_*` returns a result, and `is_*` returns a `bool`.
46
+
47
+ ```python
48
+ from network_validators import is_host, validate_subnet
49
+
50
+ r = validate_subnet("10.0.0.5/24", allow_host_bits=False)
51
+ r.valid # False
52
+ r.code # "subnet.host_bits_set"
53
+ r.details # {"network": "10.0.0.0/24"}
54
+
55
+ if r: # a result is truthy only when valid
56
+ ...
57
+
58
+ is_host("example.com") # True
59
+ ```
60
+
61
+ Map codes to your own messages:
62
+
63
+ ```python
64
+ from network_validators import ErrorCode, validate_subnet
65
+
66
+ MESSAGES: dict[ErrorCode, str] = {
67
+ "empty": "This field is required.",
68
+ "subnet.host_bits_set": "Did you mean {network}?",
69
+ "port.out_of_range": "Port must be between {min} and {max}.",
70
+ }
71
+
72
+ r = validate_subnet(value, allow_host_bits=False)
73
+ if r.code is not None: # same as `if not r`, and type checkers then see code as an ErrorCode
74
+ message = MESSAGES.get(r.code, "Invalid value.").format(**r.details)
75
+ ```
76
+
77
+ `ErrorCode` is a `Literal` type of every code, so a type checker flags a misspelled code in your map. `ERROR_CODES` lists them at runtime, for example to check that a message catalog covers them all.
78
+
79
+ Empty strings fail with code `empty`. If a field is optional, skip validation when it's empty.
80
+
81
+ Invalid options, such as `version=5`, an unknown option name or a bad entry in `subnets`, raise `TypeError` or `ValueError` instead of returning a result.
82
+
83
+ ## Validators
84
+
85
+ | Function | Accepts | Options |
86
+ |---|---|---|
87
+ | `validate_ip_address` | `192.0.2.1`, `2001:db8::1` | `version`, `allow_zone_id`, `allow_unspecified`, `allow_private` |
88
+ | `validate_private_ip_address` | `10.0.0.1`, `fd00::1` | `version`, `allow_zone_id`, `additional_ranges` |
89
+ | `validate_netmask` | `255.255.255.0` | |
90
+ | `validate_subnet` | `10.0.0.0/8`, `10.0.0.0 255.0.0.0`, `2001:db8::/32` | `version`, `allow_netmask`, `allow_host_bits` |
91
+ | `validate_private_subnet` | `192.168.1.0/24` | as `validate_subnet`, plus `additional_ranges` |
92
+ | `validate_ip_range` | `10.0.0.1-10.0.0.50` | `version`, `allow_single` |
93
+ | `validate_ip_in_subnets` / `validate_ip_not_in_subnets` | an IP address | `subnets` (required), `version` |
94
+ | `validate_subnet_in_subnets` / `validate_subnet_not_overlapping` | a subnet | `subnets` (required), `version` |
95
+ | `validate_ip_range_not_overlapping` | an IP range | `subnets` (required), `version` |
96
+ | `validate_hostname` / `validate_fqdn` | `server1` / `www.example.com` | `allow_wildcard`, `allow_underscore`, `allow_trailing_dot` |
97
+ | `validate_host` | a hostname, FQDN or IP address | IP and name options, plus `allow_single_label` |
98
+ | `validate_port` / `validate_port_range` | `443` / `8000-8080` | `allow_zero` |
99
+ | `validate_port_list` | `80, 443, 8000-8080` | `allow_zero`, `allow_ranges` |
100
+ | `validate_mac_address` | `00:1a:2b:3c:4d:5e`, `001a.2b3c.4d5e` | `formats` |
101
+
102
+ `version` is `4`, `6` or `"any"` (the default).
103
+
104
+ The [specification](https://github.com/icmp-type0/network-validators-py/blob/main/spec/SPEC.md) gives each validator's exact rules and the order of its checks. All error codes are listed in [codes.json](https://github.com/icmp-type0/network-validators-py/blob/main/spec/codes.json).
105
+
106
+ ## License
107
+
108
+ MIT
@@ -0,0 +1,82 @@
1
+ # network-validators
2
+
3
+ Validators for network-related input: IP addresses, subnets, IP ranges, hostnames, ports and MAC addresses. Each check returns a stable error code, not a message, so you write the messages your users see.
4
+
5
+ - No dependencies. Python 3.11+.
6
+ - Strict about common traps: IPv4 leading zeros (CVE-2021-29921), non-ASCII digits, surrounding whitespace, IPv6 zone IDs.
7
+ - Behaves the same as the [TypeScript package](https://www.npmjs.com/package/network-validators). Both follow one [specification](https://github.com/icmp-type0/network-validators-py/blob/main/spec/SPEC.md) and run the same test cases.
8
+
9
+ > Status: 0.1. Before 1.0, a minor version (0.2, 0.3, …) may include breaking changes. Every change is listed in the [changelog](https://github.com/icmp-type0/network-validators-py/blob/main/CHANGELOG.md).
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ pip install network-validators
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ Every validator has two forms: `validate_*` returns a result, and `is_*` returns a `bool`.
20
+
21
+ ```python
22
+ from network_validators import is_host, validate_subnet
23
+
24
+ r = validate_subnet("10.0.0.5/24", allow_host_bits=False)
25
+ r.valid # False
26
+ r.code # "subnet.host_bits_set"
27
+ r.details # {"network": "10.0.0.0/24"}
28
+
29
+ if r: # a result is truthy only when valid
30
+ ...
31
+
32
+ is_host("example.com") # True
33
+ ```
34
+
35
+ Map codes to your own messages:
36
+
37
+ ```python
38
+ from network_validators import ErrorCode, validate_subnet
39
+
40
+ MESSAGES: dict[ErrorCode, str] = {
41
+ "empty": "This field is required.",
42
+ "subnet.host_bits_set": "Did you mean {network}?",
43
+ "port.out_of_range": "Port must be between {min} and {max}.",
44
+ }
45
+
46
+ r = validate_subnet(value, allow_host_bits=False)
47
+ if r.code is not None: # same as `if not r`, and type checkers then see code as an ErrorCode
48
+ message = MESSAGES.get(r.code, "Invalid value.").format(**r.details)
49
+ ```
50
+
51
+ `ErrorCode` is a `Literal` type of every code, so a type checker flags a misspelled code in your map. `ERROR_CODES` lists them at runtime, for example to check that a message catalog covers them all.
52
+
53
+ Empty strings fail with code `empty`. If a field is optional, skip validation when it's empty.
54
+
55
+ Invalid options, such as `version=5`, an unknown option name or a bad entry in `subnets`, raise `TypeError` or `ValueError` instead of returning a result.
56
+
57
+ ## Validators
58
+
59
+ | Function | Accepts | Options |
60
+ |---|---|---|
61
+ | `validate_ip_address` | `192.0.2.1`, `2001:db8::1` | `version`, `allow_zone_id`, `allow_unspecified`, `allow_private` |
62
+ | `validate_private_ip_address` | `10.0.0.1`, `fd00::1` | `version`, `allow_zone_id`, `additional_ranges` |
63
+ | `validate_netmask` | `255.255.255.0` | |
64
+ | `validate_subnet` | `10.0.0.0/8`, `10.0.0.0 255.0.0.0`, `2001:db8::/32` | `version`, `allow_netmask`, `allow_host_bits` |
65
+ | `validate_private_subnet` | `192.168.1.0/24` | as `validate_subnet`, plus `additional_ranges` |
66
+ | `validate_ip_range` | `10.0.0.1-10.0.0.50` | `version`, `allow_single` |
67
+ | `validate_ip_in_subnets` / `validate_ip_not_in_subnets` | an IP address | `subnets` (required), `version` |
68
+ | `validate_subnet_in_subnets` / `validate_subnet_not_overlapping` | a subnet | `subnets` (required), `version` |
69
+ | `validate_ip_range_not_overlapping` | an IP range | `subnets` (required), `version` |
70
+ | `validate_hostname` / `validate_fqdn` | `server1` / `www.example.com` | `allow_wildcard`, `allow_underscore`, `allow_trailing_dot` |
71
+ | `validate_host` | a hostname, FQDN or IP address | IP and name options, plus `allow_single_label` |
72
+ | `validate_port` / `validate_port_range` | `443` / `8000-8080` | `allow_zero` |
73
+ | `validate_port_list` | `80, 443, 8000-8080` | `allow_zero`, `allow_ranges` |
74
+ | `validate_mac_address` | `00:1a:2b:3c:4d:5e`, `001a.2b3c.4d5e` | `formats` |
75
+
76
+ `version` is `4`, `6` or `"any"` (the default).
77
+
78
+ The [specification](https://github.com/icmp-type0/network-validators-py/blob/main/spec/SPEC.md) gives each validator's exact rules and the order of its checks. All error codes are listed in [codes.json](https://github.com/icmp-type0/network-validators-py/blob/main/spec/codes.json).
79
+
80
+ ## License
81
+
82
+ MIT
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "network-validators"
7
+ dynamic = ["version"]
8
+ description = "Validators for IP addresses, subnets, ranges, hostnames, ports and MAC addresses, with stable error codes."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.11"
12
+ dependencies = []
13
+ keywords = ["validation", "ip", "ipv4", "ipv6", "cidr", "subnet", "hostname", "fqdn", "port", "mac"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Programming Language :: Python :: 3.14",
24
+ "Topic :: System :: Networking",
25
+ "Typing :: Typed",
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/icmp-type0/network-validators-py"
30
+ Specification = "https://github.com/icmp-type0/network-validators-py/blob/main/spec/SPEC.md"
31
+ Issues = "https://github.com/icmp-type0/network-validators-py/issues"
32
+
33
+ [project.optional-dependencies]
34
+ test = ["pytest>=8"]
35
+
36
+ [tool.hatch.version]
37
+ path = "src/network_validators/__init__.py"
38
+
39
+ [tool.hatch.build.targets.sdist]
40
+ include = ["/src", "/tests", "/README.md", "/LICENSE"]
41
+
42
+ [tool.hatch.build.targets.wheel]
43
+ packages = ["src/network_validators"]
44
+
45
+ [tool.pytest.ini_options]
46
+ testpaths = ["tests"]
@@ -0,0 +1,147 @@
1
+ """Validators for network-related input: IP addresses, subnets, ranges, hostnames, ports and MAC addresses.
2
+
3
+ Every ``validate_*`` function returns a :class:`ValidationResult` with a stable error ``code``;
4
+ every ``is_*`` function returns a plain ``bool``. Behavior is defined by the shared specification
5
+ (spec/SPEC.md) and matches the TypeScript package.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from ._codes import ERROR_CODES, ErrorCode
13
+ from ._core import ValidationResult
14
+ from .domain import validate_fqdn, validate_host, validate_hostname
15
+ from .ip import validate_ip_address, validate_private_ip_address
16
+ from .ip_range import validate_ip_range
17
+ from .mac import validate_mac_address
18
+ from .port import validate_port, validate_port_list, validate_port_range
19
+ from .relations import (
20
+ validate_ip_in_subnets,
21
+ validate_ip_not_in_subnets,
22
+ validate_ip_range_not_overlapping,
23
+ validate_subnet_in_subnets,
24
+ validate_subnet_not_overlapping,
25
+ )
26
+ from .subnet import validate_netmask, validate_private_subnet, validate_subnet
27
+
28
+ __version__ = "0.1.0"
29
+ SPEC_VERSION = "0.1.0"
30
+
31
+
32
+ def is_ip_address(value: Any, **options: Any) -> bool:
33
+ return validate_ip_address(value, **options).valid
34
+
35
+
36
+ def is_private_ip_address(value: Any, **options: Any) -> bool:
37
+ return validate_private_ip_address(value, **options).valid
38
+
39
+
40
+ def is_netmask(value: Any) -> bool:
41
+ return validate_netmask(value).valid
42
+
43
+
44
+ def is_subnet(value: Any, **options: Any) -> bool:
45
+ return validate_subnet(value, **options).valid
46
+
47
+
48
+ def is_private_subnet(value: Any, **options: Any) -> bool:
49
+ return validate_private_subnet(value, **options).valid
50
+
51
+
52
+ def is_ip_range(value: Any, **options: Any) -> bool:
53
+ return validate_ip_range(value, **options).valid
54
+
55
+
56
+ def is_ip_in_subnets(value: Any, **options: Any) -> bool:
57
+ return validate_ip_in_subnets(value, **options).valid
58
+
59
+
60
+ def is_ip_not_in_subnets(value: Any, **options: Any) -> bool:
61
+ return validate_ip_not_in_subnets(value, **options).valid
62
+
63
+
64
+ def is_subnet_in_subnets(value: Any, **options: Any) -> bool:
65
+ return validate_subnet_in_subnets(value, **options).valid
66
+
67
+
68
+ def is_subnet_not_overlapping(value: Any, **options: Any) -> bool:
69
+ return validate_subnet_not_overlapping(value, **options).valid
70
+
71
+
72
+ def is_ip_range_not_overlapping(value: Any, **options: Any) -> bool:
73
+ return validate_ip_range_not_overlapping(value, **options).valid
74
+
75
+
76
+ def is_hostname(value: Any, **options: Any) -> bool:
77
+ return validate_hostname(value, **options).valid
78
+
79
+
80
+ def is_fqdn(value: Any, **options: Any) -> bool:
81
+ return validate_fqdn(value, **options).valid
82
+
83
+
84
+ def is_host(value: Any, **options: Any) -> bool:
85
+ return validate_host(value, **options).valid
86
+
87
+
88
+ def is_port(value: Any, **options: Any) -> bool:
89
+ return validate_port(value, **options).valid
90
+
91
+
92
+ def is_port_range(value: Any, **options: Any) -> bool:
93
+ return validate_port_range(value, **options).valid
94
+
95
+
96
+ def is_port_list(value: Any, **options: Any) -> bool:
97
+ return validate_port_list(value, **options).valid
98
+
99
+
100
+ def is_mac_address(value: Any, **options: Any) -> bool:
101
+ return validate_mac_address(value, **options).valid
102
+
103
+
104
+ # Listed explicitly: type checkers can't read a computed __all__, and under
105
+ # mypy --strict they would treat every validator as not exported.
106
+ __all__ = [
107
+ "ERROR_CODES",
108
+ "ErrorCode",
109
+ "SPEC_VERSION",
110
+ "ValidationResult",
111
+ "is_fqdn",
112
+ "is_host",
113
+ "is_hostname",
114
+ "is_ip_address",
115
+ "is_ip_in_subnets",
116
+ "is_ip_not_in_subnets",
117
+ "is_ip_range",
118
+ "is_ip_range_not_overlapping",
119
+ "is_mac_address",
120
+ "is_netmask",
121
+ "is_port",
122
+ "is_port_list",
123
+ "is_port_range",
124
+ "is_private_ip_address",
125
+ "is_private_subnet",
126
+ "is_subnet",
127
+ "is_subnet_in_subnets",
128
+ "is_subnet_not_overlapping",
129
+ "validate_fqdn",
130
+ "validate_host",
131
+ "validate_hostname",
132
+ "validate_ip_address",
133
+ "validate_ip_in_subnets",
134
+ "validate_ip_not_in_subnets",
135
+ "validate_ip_range",
136
+ "validate_ip_range_not_overlapping",
137
+ "validate_mac_address",
138
+ "validate_netmask",
139
+ "validate_port",
140
+ "validate_port_list",
141
+ "validate_port_range",
142
+ "validate_private_ip_address",
143
+ "validate_private_subnet",
144
+ "validate_subnet",
145
+ "validate_subnet_in_subnets",
146
+ "validate_subnet_not_overlapping",
147
+ ]
@@ -0,0 +1,255 @@
1
+ """Address and subnet parsing (SPEC §2, §4.2). No dependency on the stdlib ipaddress module,
2
+ so behavior matches the TypeScript implementation exactly."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import string
7
+ from dataclasses import dataclass
8
+ from typing import Any, Dict, List, Literal, Optional, Sequence
9
+
10
+ from ._codes import ErrorCode
11
+ from ._core import Invalid, is_ascii_digits
12
+
13
+ _HEX = frozenset("0123456789abcdefABCDEF")
14
+ _ZONE_CHARS = frozenset(string.ascii_letters + string.digits + "._~-")
15
+
16
+
17
+ class AddressError(Exception):
18
+ """kind is 'invalid' or 'leading_zero'."""
19
+
20
+ def __init__(self, kind: Literal["invalid", "leading_zero"] = "invalid") -> None:
21
+ super().__init__(kind)
22
+ self.kind = kind
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Address:
27
+ version: int
28
+ value: int
29
+ zone: Optional[str] = None
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Network:
34
+ version: int
35
+ address: int # as written, host bits included
36
+ prefix: int
37
+
38
+ @property
39
+ def bits(self) -> int:
40
+ return 32 if self.version == 4 else 128
41
+
42
+ @property
43
+ def mask(self) -> int:
44
+ return ((1 << self.prefix) - 1) << (self.bits - self.prefix)
45
+
46
+ @property
47
+ def first(self) -> int:
48
+ return self.address & self.mask
49
+
50
+ @property
51
+ def last(self) -> int:
52
+ return self.first | (~self.mask & ((1 << self.bits) - 1))
53
+
54
+
55
+ # --- parsing -----------------------------------------------------------------
56
+
57
+
58
+ def parse_ipv4(s: str) -> int:
59
+ parts = s.split(".")
60
+ if len(parts) != 4:
61
+ raise AddressError()
62
+ value = 0
63
+ leading_zero = False
64
+ for part in parts:
65
+ if not (1 <= len(part) <= 3) or not is_ascii_digits(part):
66
+ raise AddressError()
67
+ n = int(part)
68
+ if n > 255:
69
+ raise AddressError()
70
+ if len(part) > 1 and part[0] == "0":
71
+ leading_zero = True
72
+ value = (value << 8) | n
73
+ if leading_zero:
74
+ raise AddressError("leading_zero")
75
+ return value
76
+
77
+
78
+ def parse_ipv6(s: str) -> Address:
79
+ zone: Optional[str] = None
80
+ if "%" in s:
81
+ s, zone = s.split("%", 1)
82
+ if zone == "" or any(c not in _ZONE_CHARS for c in zone):
83
+ raise AddressError()
84
+
85
+ if "." in s:
86
+ idx = s.rfind(":")
87
+ if idx == -1:
88
+ raise AddressError()
89
+ try:
90
+ v4 = parse_ipv4(s[idx + 1 :])
91
+ except AddressError:
92
+ raise AddressError() from None
93
+ s = f"{s[: idx + 1]}{v4 >> 16:x}:{v4 & 0xFFFF:x}"
94
+
95
+ if s.count("::") > 1:
96
+ raise AddressError()
97
+ if "::" in s:
98
+ head, tail = s.split("::", 1)
99
+ h = head.split(":") if head else []
100
+ t = tail.split(":") if tail else []
101
+ if len(h) + len(t) > 7:
102
+ raise AddressError()
103
+ groups = h + ["0"] * (8 - len(h) - len(t)) + t
104
+ else:
105
+ groups = s.split(":")
106
+ if len(groups) != 8:
107
+ raise AddressError()
108
+
109
+ value = 0
110
+ for g in groups:
111
+ if not (1 <= len(g) <= 4) or any(c not in _HEX for c in g):
112
+ raise AddressError()
113
+ value = (value << 16) | int(g, 16)
114
+ return Address(6, value, zone)
115
+
116
+
117
+ def parse_ip(s: str) -> Address:
118
+ """SPEC §2.3. Raises AddressError."""
119
+ if ":" in s:
120
+ return parse_ipv6(s)
121
+ return Address(4, parse_ipv4(s))
122
+
123
+
124
+ def netmask_prefix(s: str) -> int:
125
+ """Prefix length of a dotted IPv4 netmask. Raises AddressError or ValueError (not contiguous)."""
126
+ value = parse_ipv4(s)
127
+ inverted = ~value & 0xFFFFFFFF
128
+ if inverted & (inverted + 1):
129
+ raise ValueError("netmask not contiguous")
130
+ return 32 - inverted.bit_length()
131
+
132
+
133
+ # --- formatting (SPEC §2.4) ----------------------------------------------------
134
+
135
+
136
+ def format_address(version: int, value: int) -> str:
137
+ if version == 4:
138
+ return ".".join(str((value >> shift) & 0xFF) for shift in (24, 16, 8, 0))
139
+ groups = [(value >> (16 * (7 - i))) & 0xFFFF for i in range(8)]
140
+ best_start, best_len = -1, 0
141
+ i = 0
142
+ while i < 8:
143
+ if groups[i] == 0:
144
+ j = i
145
+ while j < 8 and groups[j] == 0:
146
+ j += 1
147
+ if j - i > best_len:
148
+ best_start, best_len = i, j - i
149
+ i = j
150
+ else:
151
+ i += 1
152
+ hexes = [f"{g:x}" for g in groups]
153
+ if best_len < 2:
154
+ return ":".join(hexes)
155
+ head = ":".join(hexes[:best_start])
156
+ tail = ":".join(hexes[best_start + best_len :])
157
+ return f"{head}::{tail}"
158
+
159
+
160
+ def format_network(net: Network) -> str:
161
+ return f"{format_address(net.version, net.first)}/{net.prefix}"
162
+
163
+
164
+ # --- subnets (SPEC §4.2) -------------------------------------------------------
165
+
166
+
167
+ _WRONG_VERSION: Dict[str, ErrorCode] = {"ip": "ip.wrong_version", "subnet": "subnet.wrong_version", "range": "range.wrong_version"}
168
+
169
+
170
+ def check_version_matches(prefix: Literal["ip", "subnet", "range"], version: Any, actual: int) -> None:
171
+ if version != "any" and actual != version:
172
+ raise Invalid(_WRONG_VERSION[prefix], {"version": actual})
173
+
174
+
175
+ def parse_subnet(
176
+ value: str,
177
+ *,
178
+ version: Any = "any",
179
+ allow_netmask: bool = True,
180
+ allow_host_bits: bool = True,
181
+ ) -> Network:
182
+ """Checks 1-7 of SPEC §4.2 on a value that already passed the common checks."""
183
+ if "/" in value:
184
+ left, _, right = value.partition("/")
185
+ if "/" in right:
186
+ raise Invalid("subnet.invalid")
187
+ elif value.count(" ") == 1:
188
+ left, _, right = value.partition(" ")
189
+ if "." not in right:
190
+ raise Invalid("subnet.invalid")
191
+ else:
192
+ raise Invalid("subnet.invalid")
193
+ if left == "" or right == "":
194
+ raise Invalid("subnet.invalid")
195
+
196
+ try:
197
+ addr = parse_ip(left)
198
+ except AddressError:
199
+ raise Invalid("subnet.invalid_address") from None
200
+ if addr.zone is not None:
201
+ raise Invalid("subnet.invalid_address")
202
+ check_version_matches("subnet", version, addr.version)
203
+
204
+ if "." in right:
205
+ if not allow_netmask:
206
+ raise Invalid("subnet.netmask_not_allowed")
207
+ if addr.version == 6:
208
+ raise Invalid("subnet.invalid_netmask")
209
+ try:
210
+ prefix = netmask_prefix(right)
211
+ except (AddressError, ValueError):
212
+ raise Invalid("subnet.invalid_netmask") from None
213
+ else:
214
+ max_prefix = 32 if addr.version == 4 else 128
215
+ if (
216
+ not is_ascii_digits(right)
217
+ or len(right) > 3
218
+ or (len(right) > 1 and right[0] == "0")
219
+ or int(right) > max_prefix
220
+ ):
221
+ raise Invalid("subnet.invalid_prefix")
222
+ prefix = int(right)
223
+
224
+ net = Network(addr.version, addr.value, prefix)
225
+ if not allow_host_bits and net.address != net.first:
226
+ raise Invalid("subnet.host_bits_set", {"network": format_network(net)})
227
+ return net
228
+
229
+
230
+ def parse_subnet_list(name: str, entries: Any) -> List[Network]:
231
+ """SPEC §2.6. Raises TypeError/ValueError for bad configuration."""
232
+ if isinstance(entries, (str, bytes)) or not isinstance(entries, Sequence):
233
+ raise TypeError(f"{name} must be a list of subnet strings")
234
+ nets = []
235
+ for entry in entries:
236
+ if not isinstance(entry, str) or entry == "":
237
+ raise ValueError(f"{name}: invalid subnet {entry!r}")
238
+ try:
239
+ nets.append(parse_subnet(entry))
240
+ except Invalid as e:
241
+ raise ValueError(f"{name}: invalid subnet {entry!r} ({e.code})") from None
242
+ return nets
243
+
244
+
245
+ PRIVATE_NETWORKS = parse_subnet_list(
246
+ "PRIVATE_NETWORKS", ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]
247
+ )
248
+
249
+
250
+ def in_network(version: int, value: int, net: Network) -> bool:
251
+ return version == net.version and net.first <= value <= net.last
252
+
253
+
254
+ def is_private(addr: Address) -> bool:
255
+ return any(in_network(addr.version, addr.value, n) for n in PRIVATE_NETWORKS)