WSL2 use “localhost” to access Windows service

China☆狼群 提交于 2021-02-05 09:27:11

问题


I'm using WSL2 on Windows 10.

My dev stack is using a local webserver (localwp or wamp) on the host OS. I use WSL2 as the main terminal (SSH, Git, SASS, automation tools, ...).

What I need is a way to connect to my host services (MySql) from the WSL2 system using a server name instead of a random IP address.

It is already possible for the Windows host to connect to WSL2 services with "localhost". Is there a solution to do it the other way?


回答1:


Well, your title and your question body don't seem quite aligned.

The question title says "use localhost", but then in the body you say "using a server name."

Accessing the Windows 10 service via the name "localhost" from WSL2? Let's just go with "no". I can think of a possibility of how to make it work, but it would be complicated.

But I think the second is really what you are looking for, so a couple of options that I can think of for accessing the Windows host services by hostname in WSL2:

  • First, and hopefully the easiest, WSL2 supports mDNS (WSL1 did not), so you should be able to access the Windows host as {hostname}.local (where {hostname} is the name of the Windows host (literally, in bash, ping $(hostname).local, since the assigned WSL2 hostname is that of the host Windows 10 computer). That works for me. While I don't recall having to do anything special to enable this, this Super User answer seems to indicate that you have to turn it on manually.

  • The second option would be to add your Windows host IP to /etc/hosts. If your Windows IP is static, then you could just add it manually to /etc/hosts and be done. If it's dynamic, then you might want to script it. You can retrieve it from inside WSL2 via:

    powershell.exe "(Test-Connection -ComputerName (hostname) -Count 1).IPV4Address.IPAddressToString" (and other methods) and then use something like sed to change /etc/hosts.



来源:https://stackoverflow.com/questions/65625762/wsl2-use-localhost-to-access-windows-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!