Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

local - WSL2 use "localhost" to access Windows service

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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...