|
4 | 4 | package store
|
5 | 5 |
|
6 | 6 | import (
|
| 7 | + "context" |
7 | 8 | "fmt"
|
| 9 | + "os/exec" |
8 | 10 | "regexp"
|
9 | 11 | "strings"
|
10 | 12 |
|
@@ -115,6 +117,34 @@ func GetWslStatus(instName string) (string, error) {
|
115 | 117 | return instState, nil
|
116 | 118 | }
|
117 | 119 |
|
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 |
120 | 150 | }
|
0 commit comments