about summary refs log tree commit diff
path: root/tools/ipconverter/main.go
blob: 121197020b0b42d8d5631ca9b84896b2e18e307b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
}