Access a localhost running in Windows from inside WSL2? [closed]

Short answer for most recent Windows versions

mDNS has been a feature of WSL2 for a while now. Concatenating your WSL2 hostname (or the equivalent command/function in your programming/language environment) with ".local" should get you access.

For example, from Bash, try:

ping "$(hostname).local"

For instance, if your hostname is “MyComputer”, then the mDNS should be MyComputer.local.

If ICMP is blocked (as it seems to be on new Windows 11 installs), or if you want to test the connection to the actual port, then use netcat. It’s available by default in the WSL Ubuntu installation, but may need to be installed in other distributions like openSUSE:

nc -zv "$(hostname).local" <portnumber>

Why localhost doesn’t work

WSL2 is running with a virtual network (vNIC) that is created by the Windows Virtual Machine Platform (a subset of Hyper-V). Inside WSL2, localhost is the address of the vNIC.

What you need

WSL2 also sets up a virtual router on the Windows host to allow connectivity to both the outside world as well as the Windows host. You can see this via:

ip route

This is the address you need to use for the Windows host.

You could, of course, parse it from the route (or, as in an earlier answer, from /etc/resolv.conf), but WSL sets up a convenience mDNS (the .local domain) using the Windows “computer name”, which is also used as the hostname of the WSL instance.

So concatenating $(hostname) (or it’s equivalent in your programming/language environment) with ".local" should get you access.

Other considerations:

  • mDNS is reliant on the Windows host to resolve the name. If you have changed your /etc/resolv.conf under WSL, then this will likely not work.

  • Remember to open any necessary firewall ports. WSL2 is considered a separate network from that of the Windows host. Windows will consider network connections from WSL2 to be coming from an external source. (Credit to @RamilGilfanov for a comment pointing this out)

    The first time a connection is made from WSL2 to a particular port, Windows Defender (if that is your firewall) will typically display a dialog asking if you want to grant access. However, in my experience, this dialog often gets buried under the main window due to timing of mouse-clicks, keyboard, etc., so it’s easy to miss.

  • Remember to have your Windows service accept connections from remote hosts.

    Many servers are configured by default to bind to localhost/127.0.0.1. Because WSL2 appears to Windows as a remote network, you’ll typically need to update your configuration to bind to 0.0.0.0 or a specific address.

    Note that, since the address for WSL2 changes after each reboot, it can be difficult to update your configuration each time. If at all possible, use 0.0.0.0 unless there are security concerns. Since WSL is designed for development rather than production, this shouldn’t be an issue.

Leave a Comment