Skip to content

Instantly share code, notes, and snippets.

@killshot13
Last active February 25, 2022 13:52
Show Gist options
  • Save killshot13/1fe64536cfe61051472a11836e8e387d to your computer and use it in GitHub Desktop.
Save killshot13/1fe64536cfe61051472a11836e8e387d to your computer and use it in GitHub Desktop.
Fix for WSL2 localhost access issue

ps1_script

$hostname = "wsl"

# 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"

if ($hosts -match $find) {
    $hosts = $hosts -replace $find, $entry
}
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"
}
Problem:
Localhost redirection often fails for some reason, such as when PC sleeps and wakes up, and localhost access to Linux services does not work anymore.
Solution:
To fix this, there is a PowerShell script that gets the IP address of WSL instance, then creates or updates an entry in hosts file. This lets us access WSL by a hostname like wsl instead of localhost.
Credit/Reference
https://abdus.dev/posts/fixing-wsl2-localhost-access-issue/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment