From 422f294129f2beb7c2a89ae3dad7a68b6b165e73 Mon Sep 17 00:00:00 2001 From: Zhongcheng Lao Date: Thu, 14 Nov 2019 21:08:11 +0800 Subject: [PATCH] Prefer IPv4 over v6 and global unicast IP by default in Hyper-V driver Signed-off-by: Zhongcheng Lao --- drivers/hyperv/hyperv.go | 41 +++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/drivers/hyperv/hyperv.go b/drivers/hyperv/hyperv.go index 70e840fc06..be8dc2e04f 100644 --- a/drivers/hyperv/hyperv.go +++ b/drivers/hyperv/hyperv.go @@ -18,7 +18,7 @@ import ( ) const ( - DefaultProtocol = iota + Default = iota PreferIPv4 PreferIPv6 ) @@ -58,7 +58,7 @@ func NewDriver(hostName, storePath string) *Driver { MemSize: defaultMemory, CPU: defaultCPU, DisableDynamicMemory: defaultDisableDynamicMemory, - PreferredNetworkProtocol: DefaultProtocol, + PreferredNetworkProtocol: Default, WaitTimeoutInSeconds: defaultWaitTimeoutInSeconds, } } @@ -464,7 +464,7 @@ func (d *Driver) Kill() error { } func isIPv4(address string) bool { - return strings.Count(address, ":") < 2 + return strings.Count(address, ":") < 1 } func (d *Driver) GetIP() (string, error) { @@ -486,20 +486,33 @@ func (d *Driver) GetIP() (string, error) { return "", fmt.Errorf("IP not found") } + var preferredIP string switch d.PreferredNetworkProtocol { case PreferIPv4: for _, ipStr := range resp { ip := net.ParseIP(ipStr) - if isIPv4(ipStr) && ip.To4() != nil && ip.IsGlobalUnicast() { - return ipStr, nil + if isIPv4(ipStr) && ip.To4() != nil { + if preferredIP == "" { + preferredIP = ipStr + } + if ip.IsGlobalUnicast() { + preferredIP = ipStr + break + } } } case PreferIPv6: for _, ipStr := range resp { ip := net.ParseIP(ipStr) - if !isIPv4(ipStr) && ip.IsGlobalUnicast() { - return ipStr, nil + if !isIPv4(ipStr) { + if preferredIP == "" { + preferredIP = ipStr + } + if ip.IsGlobalUnicast() { + preferredIP = ipStr + break + } } } @@ -507,12 +520,22 @@ func (d *Driver) GetIP() (string, error) { for _, ipStr := range resp { ip := net.ParseIP(ipStr) if ip.IsGlobalUnicast() { - return ipStr, nil + if preferredIP == "" { + preferredIP = ipStr + } + if isIPv4(ipStr) && ip.To4() != nil { + preferredIP = ipStr + break + } } } + + if preferredIP == "" { + preferredIP = resp[0] + } } - return "", nil + return preferredIP, nil } func (d *Driver) publicSSHKeyPath() string {