...
1
16
17 package net
18
19 import (
20 "errors"
21 "fmt"
22 "math"
23 "math/big"
24 "net"
25 "strconv"
26 )
27
28
29
30 func ParseCIDRs(cidrsString []string) ([]*net.IPNet, error) {
31 cidrs := make([]*net.IPNet, 0, len(cidrsString))
32 for i, cidrString := range cidrsString {
33 _, cidr, err := ParseCIDRSloppy(cidrString)
34 if err != nil {
35 return nil, fmt.Errorf("invalid CIDR[%d]: %v (%v)", i, cidr, err)
36 }
37 cidrs = append(cidrs, cidr)
38 }
39 return cidrs, nil
40 }
41
42
43
44 func ParsePort(port string, allowZero bool) (int, error) {
45 portInt, err := strconv.ParseUint(port, 10, 16)
46 if err != nil {
47 return 0, err
48 }
49 if portInt == 0 && !allowZero {
50 return 0, errors.New("0 is not a valid port number")
51 }
52 return int(portInt), nil
53 }
54
55
56 func BigForIP(ip net.IP) *big.Int {
57
58
59 return big.NewInt(0).SetBytes(ip.To16())
60 }
61
62
63
64 func AddIPOffset(base *big.Int, offset int) net.IP {
65 r := big.NewInt(0).Add(base, big.NewInt(int64(offset))).Bytes()
66 r = append(make([]byte, 16), r...)
67 return net.IP(r[len(r)-16:])
68 }
69
70
71
72 func RangeSize(subnet *net.IPNet) int64 {
73 ones, bits := subnet.Mask.Size()
74 if bits == 32 && (bits-ones) >= 31 || bits == 128 && (bits-ones) >= 127 {
75 return 0
76 }
77
78 if bits-ones >= 63 {
79 return math.MaxInt64
80 }
81 return int64(1) << uint(bits-ones)
82 }
83
84
85 func GetIndexedIP(subnet *net.IPNet, index int) (net.IP, error) {
86 ip := AddIPOffset(BigForIP(subnet.IP), index)
87 if !subnet.Contains(ip) {
88 return nil, fmt.Errorf("can't generate IP with index %d from subnet. subnet too small. subnet: %q", index, subnet)
89 }
90 return ip, nil
91 }
92
View as plain text