解决 wsl2 ip 的问题

解决问题最简单粗暴的方法就是解决提出问题的人,但是我不能解决我自己,哈哈
前面 wsl1 用得挺好的,但是 vscode 推了好几次 wsl2,仔细研究了下觉得,问题应该不大,那就升级了
升级完用着用着发现,这个 ip 是个大问题,试过修改交换机为 nat,但是重启后又回去了,搞的有时候网络连接没有启用 ipv4,神奇
行,那就想办法把 ip 更新到 hosts,试过 https://github.com/shayne/go-wsl2-host 不起作用,没辙那就继续折腾
分析下问题,就是获取到 wsl2 的 ip,然后更新到 hosts 里,然后想办法把这个动作搞成 wsl2 一启动就触发,折腾了好几天,找到了最佳实践

$hostname = "wsl.dev"

# find ip of eth0
$ifconfig = (wsl -- ip -4 addr show eth0)
$ipPattern = "((\d+\.?){4})"
$ip = ([regex]"inet $ipPattern").Match($ifconfig).Groups[1].Value
if (-not $ip) {
    exit
}
Write-Host $ip

$hostsPath = "$env:windir/system32/drivers/etc/hosts"

$hosts = (Get-Content -Path $hostsPath -Raw -ErrorAction Ignore)
if ($null -eq $hosts) {
    $hosts = ""
}
$hosts = $hosts.Trim()

# update or add wsl ip
$find = "$ipPattern\s+$hostname"
$entry = "$ip $hostname"
$found = $hosts -match $find
if ($found) {
    $old_wsl_ip = $matches[0] -replace " $hostname", ''
    $hosts = $hosts -replace $old_wsl_ip, $ip
} else {
    $hosts = "$hosts`n$entry".Trim()
}

try {
    $temp = "$hostsPath.new"
    New-Item -Path $temp -ItemType File -Force | Out-Null
    Set-Content -Path $temp $hosts

    Move-Item -Path $temp -Destination $hostsPath -Force
} catch {
    Write-Error "cannot update wsl ip"
}

复制上面的内容保存为 wslhost.ps1 ,然后手动关闭下wsl

wsl --shutdown

打开事件查看器,依次展开 Windows 日志 > 系统,找到事件 ID 为 102 的记录
然后选中,右键打开菜单,选择 “将任务附加到此事件”
再按照对话框填就行了,如果 powershell 的执行策略,不允许执行 .ps1 文件,打开 powershell 执行下面的语句

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser

这样,每次 wsl 启动时都会更新 ip 到 hosts 文件

发布者

gt

QQ: 1520667045 一个名叫坏人的博客,他很想成为WEB攻城狮,因为他认为每个前端开发者的审美观都是很挑的……

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据