github.com/rothwerx/packer@v0.9.0/builder/parallels/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  	Devices []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  	for _, device := range f.Devices {
    34  		stdout := new(bytes.Buffer)
    35  
    36  		cmd := exec.Command(ifconfigPath, device)
    37  		// Force LANG=C so that the output is what we expect it to be
    38  		// despite the locale.
    39  		cmd.Env = append(cmd.Env, "LANG=C")
    40  		cmd.Env = append(cmd.Env, os.Environ()...)
    41  
    42  		cmd.Stdout = stdout
    43  		cmd.Stderr = new(bytes.Buffer)
    44  
    45  		if err := cmd.Run(); err == nil {
    46  			re := regexp.MustCompile(`inet\s+(?:addr:)?(.+?)\s`)
    47  			matches := re.FindStringSubmatch(stdout.String())
    48  			if matches != nil {
    49  				return matches[1], nil
    50  			}
    51  		}
    52  	}
    53  	return "", errors.New("IP not found in ifconfig output...")
    54  }