about summary refs log tree commit diff
path: root/tools/ipconverter/ipconverter.py
diff options
context:
space:
mode:
authorFranck Cuny <franck@fcuny.net>2022-10-04 17:53:28 -0700
committerFranck Cuny <franck@fcuny.net>2022-10-04 17:53:28 -0700
commit5da35c9ae3396002e3c8d4de8edbdf85ecf2569d (patch)
treef108d6fe7e0133130b1a1a639b36ecf703b9121d /tools/ipconverter/ipconverter.py
parentops(terraform): individual actions for init/plan/apply (diff)
downloadworld-5da35c9ae3396002e3c8d4de8edbdf85ecf2569d.tar.gz
ref(tools/ipconverter): rewrite the tool in python
No need to do this with Go, a python script is fine.

We also don't need to set shell aliases for this: when we install the
tool, we can create symbolic links to `ip2int` and `int2ip`.
Diffstat (limited to 'tools/ipconverter/ipconverter.py')
-rwxr-xr-xtools/ipconverter/ipconverter.py29
1 files changed, 29 insertions, 0 deletions
diff --git a/tools/ipconverter/ipconverter.py b/tools/ipconverter/ipconverter.py
new file mode 100755
index 0000000..fffc6fa
--- /dev/null
+++ b/tools/ipconverter/ipconverter.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+
+import argparse
+import ipaddress
+import sys
+import fileinput
+
+
+argp = argparse.ArgumentParser()
+argp.add_argument("infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin)
+args = argp.parse_args()
+
+# read the input, filter out commented lines and remove new line characters
+string_ips = [
+    ip for l in args.infile.readlines() if (ip := l.strip()) and not ip.startswith("#")
+]
+
+# convert entries to int if the string is a numeric value
+ips = list(map(lambda n: int(n) if n.isnumeric() else n, string_ips))
+
+# helper function to convert based on the name of the program
+conv = lambda n: int(n) if argp.prog == "ip2int" else str(n)
+
+for ip in ips:
+    try:
+        r = conv(ipaddress.ip_address(ip))
+        print(f"{ip:15} → {r:15}")
+    except Exception as e:
+        print(f"error: {e}", file=sys.stderr)