forked from hashicorp/packer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
host_ip.go
43 lines (35 loc) · 881 Bytes
/
host_ip.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
package vmware
import (
"bytes"
"errors"
"os/exec"
"regexp"
)
// Interface to help find the host IP that is available from within
// the VMware virtual machines.
type HostIPFinder interface {
HostIP() (string, error)
}
// IfconfigIPFinder finds the host IP based on the output of `ifconfig`.
type IfconfigIPFinder struct {
Device string
}
func (f *IfconfigIPFinder) HostIP() (string, error) {
ifconfigPath, err := exec.LookPath("ifconfig")
if err != nil {
return "", err
}
stdout := new(bytes.Buffer)
cmd := exec.Command(ifconfigPath, f.Device)
cmd.Stdout = stdout
cmd.Stderr = new(bytes.Buffer)
if err := cmd.Run(); err != nil {
return "", err
}
re := regexp.MustCompile(`inet\s*(.+?)\s`)
matches := re.FindStringSubmatch(stdout.String())
if matches == nil {
return "", errors.New("IP not found in ifconfig output...")
}
return matches[1], nil
}