github.com/rothwerx/packer@v0.9.0/builder/vmware/common/host_ip_ifconfig.go (about)

     1  package common
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  	"os"
     7  	"os/exec"
     8  	"regexp"
     9  )
    10  
    11  // IfconfigIPFinder finds the host IP based on the output of `ifconfig`.
    12  type IfconfigIPFinder struct {
    13  	Device string
    14  }
    15  
    16  func (f *IfconfigIPFinder) HostIP() (string, error) {
    17  	var ifconfigPath string
    18  
    19  	// On some systems, ifconfig is in /sbin which is generally not
    20  	// on the PATH for a standard user, so we just check that first.
    21  	if _, err := os.Stat("/sbin/ifconfig"); err == nil {
    22  		ifconfigPath = "/sbin/ifconfig"
    23  	}
    24  
    25  	if ifconfigPath == "" {
    26  		var err error
    27  		ifconfigPath, err = exec.LookPath("ifconfig")
    28  		if err != nil {
    29  			return "", err
    30  		}
    31  	}
    32  
    33  	stdout := new(bytes.Buffer)
    34  
    35  	cmd := exec.Command(ifconfigPath, f.Device)
    36  	// Force LANG=C so that the output is what we expect it to be
    37  	// despite the locale.
    38  	cmd.Env = append(cmd.Env, "LANG=C")
    39  	cmd.Env = append(cmd.Env, os.Environ()...)
    40  
    41  	cmd.Stdout = stdout
    42  	cmd.Stderr = new(bytes.Buffer)
    43  	if err := cmd.Run(); err != nil {
    44  		return "", err
    45  	}
    46  
    47  	re := regexp.MustCompile(`inet[^\d]+([\d\.]+)\s`)
    48  	matches := re.FindStringSubmatch(stdout.String())
    49  	if matches == nil {
    50  		return "", errors.New("IP not found in ifconfig output...")
    51  	}
    52  
    53  	return matches[1], nil
    54  }