forked from terra-farm/go-virtualbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
natnet.go
74 lines (71 loc) · 1.47 KB
/
natnet.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
package virtualbox
import (
"bufio"
"net"
"strings"
)
// A NATNet defines a NAT network.
type NATNet struct {
Name string
IPv4 net.IPNet
IPv6 net.IPNet
DHCP bool
Enabled bool
}
// NATNets gets all NAT networks in a map keyed by NATNet.Name.
func NATNets() (map[string]NATNet, error) {
out, _, err := Manage().run("list", "natnets")
if err != nil {
return nil, err
}
s := bufio.NewScanner(strings.NewReader(out))
m := map[string]NATNet{}
n := NATNet{}
for s.Scan() {
line := s.Text()
if line == "" {
m[n.Name] = n
n = NATNet{}
continue
}
res := reColonLine.FindStringSubmatch(line)
if res == nil {
continue
}
switch key, val := res[1], res[2]; key {
case "NetworkName":
n.Name = val
case "IP":
n.IPv4.IP = net.ParseIP(val)
case "Network":
_, ipnet, err := net.ParseCIDR(val)
if err != nil {
return nil, err
}
n.IPv4.Mask = ipnet.Mask
case "IPv6 Prefix":
// TODO: IPv6 CIDR parsing works fine on macOS, check on Windows
// if val == "" {
// continue
// }
// l, err := strconv.ParseUint(val, 10, 7)
// if err != nil {
// return nil, err
// }
// n.IPv6.Mask = net.CIDRMask(int(l), net.IPv6len*8)
_, ipnet, err := net.ParseCIDR(val)
if err != nil {
return nil, err
}
n.IPv6.Mask = ipnet.Mask
case "DHCP Enabled":
n.DHCP = (val == stringYes)
case "Enabled":
n.Enabled = (val == stringYes)
}
}
if err := s.Err(); err != nil {
return nil, err
}
return m, nil
}