github.com/sneal/packer@v0.5.2/builder/vmware/iso/host_ip_vmnetnatconf.go (about)

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