29 lines
911 B
Python
29 lines
911 B
Python
import re
|
|
ipv4_pattern = re.compile(r"(\d+)\.(\d+)\.(\d+)\.(\d+)", re.ASCII)
|
|
|
|
|
|
def read_ips(f):
|
|
# TODO: make async and more robust. (regex pls)
|
|
# TODO: does readlines() block if the pipe is left open i.e. user input?
|
|
for ip in f.readlines():
|
|
if "#" in ip:
|
|
ip, _, _ = ip.partition("#")
|
|
ip = ip.strip()
|
|
if ip.count(".") != 3:
|
|
continue
|
|
yield ip
|
|
|
|
|
|
def addr_to_int(ip):
|
|
match = ipv4_pattern.fullmatch(ip)
|
|
assert match is not None, row
|
|
segs = list(map(int, match.group(1, 2, 3, 4)))
|
|
assert all(0 <= seg <= 255 for seg in segs), match.group(0)
|
|
numeric = segs[0] << 24 | segs[1] << 16 | segs[2] << 8 | segs[3]
|
|
return numeric
|
|
|
|
|
|
def ipkey(ip_string):
|
|
# this is more lenient than addr_to_int.
|
|
segs = [int(s) for s in ip_string.replace(":", ".").split(".")]
|
|
return sum(256**(3 - i) * seg for i, seg in enumerate(segs))
|