aboutsummaryrefslogtreecommitdiff
path: root/tools/ipconverter/main_test.go
diff options
context:
space:
mode:
authorFranck Cuny <franck@fcuny.net>2022-06-18 14:10:23 -0700
committerFranck Cuny <franck@fcuny.net>2022-06-18 14:18:02 -0700
commit300eb227b160f05d7aa429e9c779f2c74e095f81 (patch)
tree8b0ea3e46f6d259969aef51eec2e20d385fecfa7 /tools/ipconverter/main_test.go
parentref(scripts): remove the module for scripts (diff)
downloadinfra-300eb227b160f05d7aa429e9c779f2c74e095f81.tar.gz
feat(ipconverter): add a tool to convert IPv4 to int and vice-versa
It's sometimes useful to store IPv4 addresses as an integer. This tool helps with the conversion, and also does the reverse conversion. ``` % go run . int2ip 3232235521 3232235521 192.168.0.1 % go run . ip2int 192.168.0.1 192.168.0.1 3232235521 ``` Change-Id: Ic1e44057bca3539b4c183d387c635f69f5bf3f36 Reviewed-on: https://cl.fcuny.net/c/world/+/441 Tested-by: CI Reviewed-by: Franck Cuny <franck@fcuny.net>
Diffstat (limited to 'tools/ipconverter/main_test.go')
-rw-r--r--tools/ipconverter/main_test.go44
1 files changed, 44 insertions, 0 deletions
diff --git a/tools/ipconverter/main_test.go b/tools/ipconverter/main_test.go
new file mode 100644
index 0000000..394dc28
--- /dev/null
+++ b/tools/ipconverter/main_test.go
@@ -0,0 +1,44 @@
+package main
+
+import (
+ "math/big"
+ "testing"
+)
+
+func TestIPtoInt(t *testing.T) {
+
+ tests := map[string]*big.Int{
+ "192.168.0.1": big.NewInt(3232235521),
+ "10.0.0.1": big.NewInt(167772161),
+ }
+ for test := range tests {
+ r, err := IPtoInt(test)
+ if err != nil {
+ t.Errorf("failed to convert %s to an int: %s", test, err)
+ }
+ if r.Cmp(tests[test]) != 0 {
+ t.Errorf("convert %s to int, got %d expected %d", test, r, tests[test])
+ }
+ }
+
+ if _, err := IPtoInt("10"); err == nil {
+ t.Error("calling IPtoInt with invalid IP did not result in error")
+ }
+}
+
+
+func TestIPtoN(t *testing.T) {
+ tests := map[string]string{
+ "3232235521": "192.168.0.1",
+ "167772161": "10.0.0.1",
+ }
+ for test := range tests {
+ r, err := IPtoN(test)
+ if err != nil {
+ t.Errorf("failed to convert %s to an address: %s", test, err)
+ }
+ if r != tests[test] {
+ t.Errorf("convert %s to address, got %s expected %s", test, r, tests[test])
+ }
+ }
+}