github.com/alouche/packer@v0.3.7/builder/vmware/host_ip_vmnetnatconf.go (about)

     1  package vmware
     2  
     3  import (
     4  	"bufio"
     5  	"errors"
     6  	"fmt"
     7  	"io"
     8  	"os"
     9  	"regexp"
    10  	"strings"
    11  )
    12  
    13  // VMnetNatConfIPFinder finds the IP address of the host machine by
    14  // retrieving the IP from the vmnetnat.conf. This isn't a full proof
    15  // technique but so far it has not failed.
    16  type VMnetNatConfIPFinder struct{}
    17  
    18  func (*VMnetNatConfIPFinder) HostIP() (string, error) {
    19  	driver := &Workstation9Driver{}
    20  
    21  	vmnetnat := driver.VmnetnatConfPath()
    22  	if vmnetnat == "" {
    23  		return "", errors.New("Could not find NAT vmnet conf file")
    24  	}
    25  
    26  	if _, err := os.Stat(vmnetnat); err != nil {
    27  		return "", fmt.Errorf("Could not find NAT vmnet conf file: %s", vmnetnat)
    28  	}
    29  
    30  	f, err := os.Open(vmnetnat)
    31  	if err != nil {
    32  		return "", err
    33  	}
    34  	defer f.Close()
    35  
    36  	ipRe := regexp.MustCompile(`^\s*ip\s*=\s*(.+?)\s*$`)
    37  
    38  	r := bufio.NewReader(f)
    39  	for {
    40  		line, err := r.ReadString('\n')
    41  		if line != "" {
    42  			matches := ipRe.FindStringSubmatch(line)
    43  			if matches != nil {
    44  				ip := matches[1]
    45  				dotIndex := strings.LastIndex(ip, ".")
    46  				if dotIndex == -1 {
    47  					continue
    48  				}
    49  
    50  				ip = ip[0:dotIndex] + ".1"
    51  				return ip, nil
    52  			}
    53  		}
    54  
    55  		if err == io.EOF {
    56  			break
    57  		}
    58  
    59  		if err != nil {
    60  			return "", err
    61  		}
    62  	}
    63  
    64  	return "", errors.New("host IP not found in " + vmnetnat)
    65  }