-
Notifications
You must be signed in to change notification settings - Fork 0
/
iplib.go
45 lines (40 loc) · 935 Bytes
/
iplib.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
package main
import (
"encoding/binary"
"errors"
"net"
)
func ReverseBits(b byte) (d byte) {
d = b ^ 0xff
return d
}
func Hostmask(mask []byte) []byte {
hostmask := make([]byte, len(mask))
for j, v := range mask {
hostmask[j] = ReverseBits(v)
}
return hostmask
}
func IPSubnetHosts(firstIP *net.IP, hostmask []byte) (ips []net.IP) {
// Returns all the IPs for a given range
bs := make([]byte, 4) // bs will be our []byte
mask := binary.BigEndian.Uint32(hostmask) + 1
ips = make([]net.IP, mask)
for i := uint32(0x0); i < mask; i++ {
binary.BigEndian.PutUint32(bs, i)
s, _ := AddBytesSlices(*firstIP, bs)
ips[i] = net.IP{s[0], s[1], s[2], s[3]}
}
return ips
}
func AddBytesSlices(a []byte, b []byte) (c []byte, err error) {
l := len(a)
if l != len(b) {
return nil, errors.New("Slices must be of the same length")
}
c = make([]byte, l)
for i := 0; i < l; i++ {
c[i] = a[i] + b[i]
}
return c, nil
}