-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
73 lines (64 loc) · 1.53 KB
/
utils.go
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package mapcidr
import (
"crypto/rand"
"encoding/hex"
"net"
"strings"
)
// inc increments an IP address to the next IP in the subnet
func inc(ip net.IP) net.IP {
incIP := make([]byte, len(ip))
copy(incIP, ip)
for j := len(incIP) - 1; j >= 0; j-- {
incIP[j]++
if incIP[j] > 0 {
break
}
}
return incIP
}
// dec decrements an IP address to the previous IP in the subnet
// func dec(IP net.IP) net.IP {
// decIP := make([]byte, len(IP))
// copy(decIP, IP)
// for j := len(decIP) - 1; j >= 0; j-- {
// decIP[j]--
// if decIP[j] < 255 {
// break
// }
// }
// return decIP
// }
// TotalIPSInCidrs calculates the number of ips in the diven cidrs
func TotalIPSInCidrs(cidrs []*net.IPNet) (totalIPs uint64) {
for _, cidr := range cidrs {
totalIPs += AddressCountIpnet(cidr)
}
return
}
// AsIPV4CIDR converts ipv4 address to cidr representation
func AsIPV4CIDR(ipv4 string) *net.IPNet {
if IsIPv4(net.ParseIP(ipv4)) {
ipv4 += "/32"
}
_, network, err := net.ParseCIDR(ipv4)
if err != nil {
return nil
}
return network
}
func IsBaseIP(IP string) bool {
ipParsed := net.ParseIP(IP)
return ipParsed != nil && ipParsed.To4() != nil && strings.HasSuffix(IP, ".0")
}
func IsBroadcastIP(IP string) bool {
ipParsed := net.ParseIP(IP)
return ipParsed != nil && ipParsed.To4() != nil && strings.HasSuffix(IP, ".255")
}
func RandomHex(n int, suffix []byte) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return hex.EncodeToString(append(bytes, suffix...)), nil
}