github.phpd.cn/hashicorp/packer@v1.3.2/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 // HostIP returns the host's IP address or an error if it could not be found 17 // from the `ifconfig` output. 18 func (f *IfconfigIPFinder) HostIP() (string, error) { 19 var ifconfigPath string 20 21 // On some systems, ifconfig is in /sbin which is generally not 22 // on the PATH for a standard user, so we just check that first. 23 if _, err := os.Stat("/sbin/ifconfig"); err == nil { 24 ifconfigPath = "/sbin/ifconfig" 25 } 26 27 if ifconfigPath == "" { 28 var err error 29 ifconfigPath, err = exec.LookPath("ifconfig") 30 if err != nil { 31 return "", err 32 } 33 } 34 35 for _, device := range f.Devices { 36 stdout := new(bytes.Buffer) 37 38 cmd := exec.Command(ifconfigPath, device) 39 // Force LANG=C so that the output is what we expect it to be 40 // despite the locale. 41 cmd.Env = append(cmd.Env, "LANG=C") 42 cmd.Env = append(cmd.Env, os.Environ()...) 43 44 cmd.Stdout = stdout 45 cmd.Stderr = new(bytes.Buffer) 46 47 if err := cmd.Run(); err == nil { 48 re := regexp.MustCompile(`inet\s+(?:addr:)?(.+?)\s`) 49 matches := re.FindStringSubmatch(stdout.String()) 50 if matches != nil { 51 return matches[1], nil 52 } 53 } 54 } 55 return "", errors.New("IP not found in ifconfig output") 56 }