前言
官方最新版中已添加 windows.local 的支持 不用參考下面的修改方法
前往 wsl2host 下載使用即可
- 由於每次電腦重啟WSL2的IP都會變化, 造成使用上的不便
- 前段時間找到了這個項目 wsl2host 可以實現自動修改hosts文件
- windows端就可以通過域名的形式訪問WSL2中的服務 如 ubuntu1804.wsl
- 但是這個項目沒有在hosts文件中添加WSL2訪問windows的映射
- 此篇博文就是為了解決這個問題
- 下面介紹添加內容的過程, 結尾有提供編譯好的文件供使用
注意
- 此處僅測試了 Ubuntu-18.04 版本的 WSL2, 其余版本請自測
- 本次修改基於原項目版本 41128b4
- 運行環境信息如下
Win10 21H1 19043.1288
WSL2 Ubuntu-18.04
go version go1.17.1 windows/amd64
修改過程
- clone 原項目之后 找到 go-wsl2-host\pkg\wslcli\wslcli.go
在文件中添加如下代碼內容
// 原理是通過執行命令 wsl.exe cat /etc/resolv.conf 找到 windows IP
func GetWindowsIP() (result string, err error) {
cmd := exec.Command("wsl.exe", "cat", "/etc/resolv.conf")
out, err := cmd.Output()
if err != nil {
return "", err
}
outStr := string(out)
ipInfos := strings.Split(outStr, "nameserver ")
result = strings.TrimSpace(ipInfos[1])
return
}
- 找到 go-wsl2-host\cmd\wsl2host\pkg\service 修改文件139 -> 153 行為如下內容
windowsIp, err := wslcli.GetWindowsIP()
if err == nil {
hostname, err := os.Hostname()
err = hapi.AddEntry(&hostsapi.HostEntry{
IP: windowsIp,
Hostname: "windows.local",
Comment: wsl2hosts.DistroComment(hostname),
})
if err == nil {
updated = true
}
}
- 測試運行本文件 Run 方法, 查看hosts文件中是否有新增如下兩條內容
- 測試成功后進入 go-wsl2-host\cmd\wsl2host 使用
go build
命令打包, 生成 wsl2host.exe
使用方法
- 管理員方式運行 cmd, 進入 wsl2host.exe 所在目錄
- 運行如下命令, 根據提示輸入本機賬號密碼即可安裝
.\wsl2host.exe install
- 如不想使用了, 使用如下命令進行卸載
.\wsl2host.exe remove
- 接下來即可在 WSL2 中 通過 windows.local 訪問 windows 中的服務了