Skip to content

Commit ae2b230

Browse files
authored
Merge pull request #3842 from afbjorklund/wsl2-hostname
Add fallback for busybox hostname with wsl2
2 parents 017bcc9 + ca30c0d commit ae2b230

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

pkg/store/instance_windows.go

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
package store
55

66
import (
7+
"context"
78
"fmt"
9+
"os/exec"
810
"regexp"
911
"strings"
1012

@@ -115,6 +117,34 @@ func GetWslStatus(instName string) (string, error) {
115117
return instState, nil
116118
}
117119

118-
func GetSSHAddress(_ string) (string, error) {
119-
return "127.0.0.1", nil
120+
// GetSSHAddress runs a hostname command to get the IP from inside of a wsl2 VM.
121+
//
122+
// Expected output (whitespace preserved, [] for optional):
123+
// PS > wsl -d <distroName> bash -c hostname -I | cut -d' ' -f1
124+
// 168.1.1.1 [10.0.0.1]
125+
// But busybox hostname does not implement --all-ip-addresses:
126+
// hostname: unrecognized option: I
127+
func GetSSHAddress(instName string) (string, error) {
128+
ctx := context.TODO()
129+
distroName := "lima-" + instName
130+
// Ubuntu
131+
cmd := exec.CommandContext(ctx, "wsl.exe", "-d", distroName, "bash", "-c", `hostname -I | cut -d ' ' -f1`)
132+
out, err := cmd.CombinedOutput()
133+
if err == nil {
134+
return strings.TrimSpace(string(out)), nil
135+
}
136+
// Alpine
137+
cmd = exec.CommandContext(ctx, "wsl.exe", "-d", distroName, "sh", "-c", `ip route get 1 | awk '{gsub("^.*src ",""); print $1; exit}'`)
138+
out, err = cmd.CombinedOutput()
139+
if err == nil {
140+
return strings.TrimSpace(string(out)), nil
141+
}
142+
// fallback
143+
cmd = exec.CommandContext(ctx, "wsl.exe", "-d", distroName, "hostname", "-i")
144+
out, err = cmd.CombinedOutput()
145+
if err != nil || strings.HasPrefix(string(out), "127.") {
146+
return "", fmt.Errorf("failed to get hostname for instance %q, err: %w (out=%q)", instName, err, string(out))
147+
}
148+
149+
return strings.TrimSpace(string(out)), nil
120150
}

0 commit comments

Comments
 (0)