• WSL2 与 Win10 固定host互相访问


    前言

    • 由于每次电脑重启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-hostpkgwslcliwslcli.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-hostcmdwsl2hostpkgservice 修改文件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-hostcmdwsl2host 使用 go build 命令打包, 生成 wsl2host.exe

    使用方法

    • 管理员方式运行 cmd, 进入 wsl2host.exe 所在目录
    • 运行如下命令, 根据提示输入本机账号密码即可安装
    .wsl2host.exe install
    
    • 如不想使用了, 使用如下命令进行卸载
    .wsl2host.exe remove
    
    • 接下来即可在 WSL2 中 通过 windows.local 访问 windows 中的服务了

    已打包好的 exe 文件 点击下载

  • 相关阅读:
    「程序员」都是如何找到漂亮女朋友的?
    JAVA图片压缩到指定大小
    linux下nginx的(启动、重启、关闭)
    linux下启动rabbitmq,redis,nginx
    JAVA JAR包注册成服务,开机启动,WINSW使用
    linux下安装OpenJDK 1.8
    自定义滚动条
    面试题记录
    BOM
    SQL
  • 原文地址:https://www.cnblogs.com/heei/p/15407237.html
Copyright © 2020-2023  润新知