forked from terra-farm/go-virtualbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dhcp.go
83 lines (77 loc) · 1.78 KB
/
dhcp.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
package virtualbox
import (
"bufio"
"net"
"strings"
)
// DHCP server info.
type DHCP struct {
NetworkName string
IPv4 net.IPNet
LowerIP net.IP
UpperIP net.IP
Enabled bool
}
func addDHCP(kind, name string, d DHCP) error {
args := []string{"dhcpserver", "add",
kind, name,
"--ip", d.IPv4.IP.String(),
"--netmask", net.IP(d.IPv4.Mask).String(),
"--lowerip", d.LowerIP.String(),
"--upperip", d.UpperIP.String(),
}
if d.Enabled {
args = append(args, "--enable")
} else {
args = append(args, "--disable")
}
return vbm(args...)
}
// AddInternalDHCP adds a DHCP server to an internal network.
func AddInternalDHCP(netname string, d DHCP) error {
return addDHCP("--netname", netname, d)
}
// AddHostonlyDHCP adds a DHCP server to a host-only network.
func AddHostonlyDHCP(ifname string, d DHCP) error {
return addDHCP("--ifname", ifname, d)
}
// DHCPs gets all DHCP server settings in a map keyed by DHCP.NetworkName.
func DHCPs() (map[string]*DHCP, error) {
out, err := vbmOut("list", "dhcpservers")
if err != nil {
return nil, err
}
s := bufio.NewScanner(strings.NewReader(out))
m := map[string]*DHCP{}
dhcp := &DHCP{}
for s.Scan() {
line := s.Text()
if line == "" {
m[dhcp.NetworkName] = dhcp
dhcp = &DHCP{}
continue
}
res := reColonLine.FindStringSubmatch(line)
if res == nil {
continue
}
switch key, val := res[1], res[2]; key {
case "NetworkName":
dhcp.NetworkName = val
case "IP":
dhcp.IPv4.IP = net.ParseIP(val)
case "upperIPAddress":
dhcp.UpperIP = net.ParseIP(val)
case "lowerIPAddress":
dhcp.LowerIP = net.ParseIP(val)
case "NetworkMask":
dhcp.IPv4.Mask = ParseIPv4Mask(val)
case "Enabled":
dhcp.Enabled = (val == "Yes")
}
}
if err := s.Err(); err != nil {
return nil, err
}
return m, nil
}