-
Notifications
You must be signed in to change notification settings - Fork 467
/
utils.go
88 lines (78 loc) · 2.03 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package database
import (
"encoding/binary"
"fmt"
"net"
"strconv"
"strings"
"time"
)
func IP2Int(ip net.IP) uint32 {
if len(ip) == 16 {
return binary.BigEndian.Uint32(ip[12:16])
}
return binary.BigEndian.Uint32(ip)
}
func Int2ip(nn uint32) net.IP {
ip := make(net.IP, 4)
binary.BigEndian.PutUint32(ip, nn)
return ip
}
func IsIpv4(host string) bool {
return net.ParseIP(host) != nil
}
//Stolen from : https://github.com/llimllib/ipaddress/
// Return the final address of a net range. Convert to IPv4 if possible,
// otherwise return an ipv6
func LastAddress(n *net.IPNet) net.IP {
ip := n.IP.To4()
if ip == nil {
ip = n.IP
return net.IP{
ip[0] | ^n.Mask[0], ip[1] | ^n.Mask[1], ip[2] | ^n.Mask[2],
ip[3] | ^n.Mask[3], ip[4] | ^n.Mask[4], ip[5] | ^n.Mask[5],
ip[6] | ^n.Mask[6], ip[7] | ^n.Mask[7], ip[8] | ^n.Mask[8],
ip[9] | ^n.Mask[9], ip[10] | ^n.Mask[10], ip[11] | ^n.Mask[11],
ip[12] | ^n.Mask[12], ip[13] | ^n.Mask[13], ip[14] | ^n.Mask[14],
ip[15] | ^n.Mask[15]}
}
return net.IPv4(
ip[0]|^n.Mask[0],
ip[1]|^n.Mask[1],
ip[2]|^n.Mask[2],
ip[3]|^n.Mask[3])
}
func GetIpsFromIpRange(host string) (int64, int64, error) {
var ipStart int64
var ipEnd int64
var err error
var parsedRange *net.IPNet
if _, parsedRange, err = net.ParseCIDR(host); err != nil {
return ipStart, ipEnd, fmt.Errorf("'%s' is not a valid CIDR", host)
}
if parsedRange == nil {
return ipStart, ipEnd, fmt.Errorf("unable to parse network : %s", err)
}
ipStart = int64(IP2Int(parsedRange.IP))
ipEnd = int64(IP2Int(LastAddress(parsedRange)))
return ipStart, ipEnd, nil
}
func ParseDuration(d string) (time.Duration, error) {
durationStr := d
if strings.HasSuffix(d, "d") {
days := strings.Split(d, "d")[0]
if len(days) == 0 {
return 0, fmt.Errorf("'%s' can't be parsed as duration", d)
}
daysInt, err := strconv.Atoi(days)
if err != nil {
return 0, err
}
durationStr = strconv.Itoa(daysInt*24) + "h"
}
duration, err := time.ParseDuration(durationStr)
if err != nil {
return 0, err
}
return duration, nil
}