|
4 | 4 | import time |
5 | 5 | from collections import OrderedDict |
6 | 6 | from hashlib import blake2b |
| 7 | +from typing import Iterable |
7 | 8 | from unittest.mock import Mock |
8 | 9 |
|
9 | 10 | from kubernetes.client import api_client |
@@ -167,32 +168,21 @@ def url_path_join(*pieces): |
167 | 168 | return result |
168 | 169 |
|
169 | 170 |
|
170 | | -def ip_in_networks(ip, networks, min_prefix_len=1): |
171 | | - """Return whether `ip` is in the dict of networks |
172 | | -
|
173 | | - This is O(1) regardless of the size of networks |
174 | | -
|
175 | | - Implementation based on netaddr.IPSet.__contains__ |
176 | | -
|
177 | | - Repeatedly checks if ip/32; ip/31; ip/30; etc. is in networks |
178 | | - for all netmasks that match the given ip, |
179 | | - for a max of 32 dict key lookups for ipv4. |
| 171 | +def ip_in_networks( |
| 172 | + ip_addr: str, networks: Iterable[ipaddress.IPv4Network | ipaddress.IPv6Network] |
| 173 | +): |
| 174 | + """ |
| 175 | + Checks if `ip_addr` is contained within any of the networks in `networks` |
180 | 176 |
|
181 | | - If all netmasks have a prefix length of e.g. 24 or greater, |
182 | | - min_prefix_len prevents checking wider network masks that can't possibly match. |
| 177 | + If ip_addr is in any of the provided networks, return the first network that matches. |
| 178 | + If not, return False |
183 | 179 |
|
184 | | - Returns `(netmask, networks[netmask])` for matching netmask |
185 | | - in networks, if found; False, otherwise. |
| 180 | + Both ipv6 and ipv4 are supported |
186 | 181 | """ |
187 | | - if min_prefix_len < 1: |
188 | | - raise ValueError(f"min_prefix_len must be >= 1, got {min_prefix_len}") |
189 | | - if not networks: |
190 | | - return False |
191 | | - check_net = ipaddress.ip_network(ip) |
192 | | - while check_net.prefixlen >= min_prefix_len: |
193 | | - if check_net in networks: |
194 | | - return check_net, networks[check_net] |
195 | | - check_net = check_net.supernet(1) |
| 182 | + ip = ipaddress.ip_address(ip_addr) |
| 183 | + for network in networks: |
| 184 | + if ip in network: |
| 185 | + return network |
196 | 186 | return False |
197 | 187 |
|
198 | 188 |
|
|
0 commit comments