-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiprange.go
More file actions
97 lines (77 loc) · 2.14 KB
/
iprange.go
File metadata and controls
97 lines (77 loc) · 2.14 KB
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
89
90
91
92
93
94
95
96
97
package ipx
import "math/rand"
// IPRange represents an IP range
// Lower boundary is included and Upper boundary is not included
type IPRange struct {
Lower IP // LowerIP
Upper IP // UpperIP
}
// ParseIPRange parses x and y as an IPRange
// Order is not imported on input parameters
func ParseIPRange(x, y string) (*IPRange, error) {
xIP, err := ParseIP(x)
if err != nil {
return nil, err
}
yIP, err := ParseIP(y)
if err != nil {
return nil, err
}
ipRange := NewIPRange(xIP, yIP)
return ipRange, nil
}
// MustParseIPRange parses x and y as an IPRange
// It throws panic if x or y is not a valid IP address
// Order is not imported on input parameters
func MustParseIPRange(x, y string) *IPRange {
ipRange, err := ParseIPRange(x, y)
if err != nil {
panic(err)
}
return ipRange
}
// NewIPRange creates a new IPRange with x and y
// Order is not important
func NewIPRange(x, y IP) *IPRange {
if x.ToInt() < y.ToInt() {
return &IPRange{x, y}
}
return &IPRange{y, x}
}
// Contains reports whether the IPRange includes ip
func (i *IPRange) Contains(ip IP) bool {
ipInt := ip.ToInt()
return ipInt >= i.Lower.ToInt() && ipInt < i.Upper.ToInt()
}
// IPNumber returns the number of ip addresses in IPRange
func (i *IPRange) IPNumber() int {
return int(i.Upper.ToInt() - i.Lower.ToInt())
}
// FirstIP returns the first ip in IPRange
func (i *IPRange) FirstIP() IP {
return i.Lower
}
// LastIP returns the last ip in IPRange
func (i *IPRange) LastIP() IP {
if i.Lower.Equal(i.Upper) {
return i.Lower
}
return i.Upper.GetPrevious()
}
// GetAllIP returns all IP's in IPRange
func (i *IPRange) GetAllIP() []IP {
ipList := []IP{i.Lower}
if i.Lower.Equal(i.Upper) {
return ipList
}
ipList = append(ipList, i.Lower.GetAllNextN(uint32(i.IPNumber())-1)...)
return ipList
}
// RandomIP returns a random ip address in IPRange
func (i *IPRange) RandomIP() IP {
return FromInt(uint32(rand.Intn(i.IPNumber())) + i.Lower.ToInt())
}
// Intersects checks whether the IPRange intersects the other IPrange
func (i *IPRange) Intersects(i2 IPRange) bool {
return i.Contains(i2.Lower) || i.Contains(i2.LastIP()) || i2.Contains(i.Lower) || i2.Contains(i.LastIP())
}