aboutsummaryrefslogtreecommitdiff
path: root/tools/ipconverter/main.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.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.go')
-rw-r--r--tools/ipconverter/main.go58
1 files changed, 58 insertions, 0 deletions
diff --git a/tools/ipconverter/main.go b/tools/ipconverter/main.go
new file mode 100644
index 0000000..1211970
--- /dev/null
+++ b/tools/ipconverter/main.go
@@ -0,0 +1,58 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "math/big"
+ "net"
+ "os"
+ "path"
+ "strconv"
+)
+
+func main() {
+ cmd := path.Base(os.Args[1])
+
+ switch cmd {
+ case "ip2int":
+ for _, ip := range os.Args[2:] {
+ r, err := IPtoInt(ip)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "failed to parse %s to an int: %s", ip, err)
+ continue
+ }
+ fmt.Printf("%s\t%d\n", ip, r)
+ }
+ case "int2ip":
+ for _, ip := range os.Args[2:] {
+ r, err := IPtoN(ip)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "failed to parse %s to an addresse IP: %s", ip, err)
+ continue
+ }
+ fmt.Printf("%s\t%s", ip, r)
+ }
+ default:
+ fmt.Printf("`%s' is not a supported command", cmd)
+ os.Exit(1)
+ }
+}
+
+func IPtoInt(ip string) (*big.Int, error) {
+ i := net.ParseIP(ip)
+ if len(i.To4()) == 4 {
+ return big.NewInt(0).SetBytes(i.To4()), nil
+ } else {
+ return nil, fmt.Errorf("%s is not an IPv4 address", ip)
+ }
+}
+
+func IPtoN(ip string) (string, error) {
+ r, err := strconv.Atoi(ip)
+ if err != nil {
+ return "", fmt.Errorf("failed to parse %s to an int: %s", ip, err)
+ }
+ newIP := make(net.IP, 4)
+ binary.BigEndian.PutUint32(newIP, uint32(r))
+ return newIP.To4().String(), nil
+}