2013-12-24 00:58:41 -05:00
|
|
|
package iso
|
2013-07-31 17:46:12 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"errors"
|
2013-11-04 17:34:51 -05:00
|
|
|
"os"
|
2013-07-31 17:46:12 -04:00
|
|
|
"os/exec"
|
|
|
|
"regexp"
|
|
|
|
)
|
|
|
|
|
|
|
|
// IfconfigIPFinder finds the host IP based on the output of `ifconfig`.
|
|
|
|
type IfconfigIPFinder struct {
|
|
|
|
Device string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *IfconfigIPFinder) HostIP() (string, error) {
|
2013-11-04 17:34:51 -05:00
|
|
|
var ifconfigPath string
|
|
|
|
|
|
|
|
// On some systems, ifconfig is in /sbin which is generally not
|
|
|
|
// on the PATH for a standard user, so we just check that first.
|
|
|
|
if _, err := os.Stat("/sbin/ifconfig"); err == nil {
|
|
|
|
ifconfigPath = "/sbin/ifconfig"
|
|
|
|
}
|
|
|
|
|
|
|
|
if ifconfigPath == "" {
|
|
|
|
var err error
|
|
|
|
ifconfigPath, err = exec.LookPath("ifconfig")
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2013-07-31 17:46:12 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
stdout := new(bytes.Buffer)
|
|
|
|
|
|
|
|
cmd := exec.Command(ifconfigPath, f.Device)
|
2013-11-04 17:26:18 -05:00
|
|
|
cmd.Env = append(cmd.Env, os.Environ()...)
|
|
|
|
|
|
|
|
// Force LANG=C so that the output is what we expect it to be
|
|
|
|
// despite the locale.
|
|
|
|
cmd.Env = append(cmd.Env, "LANG=C")
|
|
|
|
|
2013-07-31 17:46:12 -04:00
|
|
|
cmd.Stdout = stdout
|
|
|
|
cmd.Stderr = new(bytes.Buffer)
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
re := regexp.MustCompile(`inet\s*(?:addr:)?(.+?)\s`)
|
|
|
|
matches := re.FindStringSubmatch(stdout.String())
|
|
|
|
if matches == nil {
|
|
|
|
return "", errors.New("IP not found in ifconfig output...")
|
|
|
|
}
|
|
|
|
|
|
|
|
return matches[1], nil
|
|
|
|
}
|