WSL2使用“本地主机"访问Windows服务 [英] WSL2 use "localhost" to access Windows service

查看:1238
本文介绍了WSL2使用“本地主机"访问Windows服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Windows 10上使用WSL2.

I'm using WSL2 on Windows 10.

我的开发堆栈在主机OS上使用本地Web服务器(localwp或wamp).我将WSL2用作主要终端(SSH,Git,SASS,自动化工具等).

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, ...).

我需要的是一种使用服务器名称而不是随机IP地址从WSL2系统连接到我的主机服务(MySql)的方法.

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.

Windows主机已经可以通过"localhost"连接到WSL2服务.有其他解决方案吗?

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?

推荐答案

好吧,您的标题和问题正文似乎不太一致.

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

通过名称"localhost"访问Windows 10服务.从WSL2?让我们以否"开始.我可以想到如何使其起作用的可能性,但这会很复杂.

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.

但是我认为第二个是您真正要寻找的东西,因此,我可以考虑使用WSL2中按主机名访问Windows主机服务的几个选项:

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:

  • 首先,希望最简单的WSL2支持mDNS(WSL1不支持),因此您应该能够以 {hostname} .local (其中{hostname} 是Windows主机的名称(从字面上看,用bash表示,请 ping $ {hostname).local ,因为分配的WSL2主机名是Windows 10计算机的主机名).这对我有用.虽然我不记得要做任何特殊的操作才能启用此功能,但此超级用户答案似乎可以表示您必须手动将其打开.

  • 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.

第二个选项是将Windows主机IP添加到/etc/hosts .如果您的Windows IP是静态的,则只需将其手动添加到/etc/hosts 即可.如果它是动态的,那么您可能要编写脚本.您可以通过以下方式从WSL2内部检索它:

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((测试连接-ComputerName(主机名)-计数1).IPV4Address.IPAddressToString" (和其他方法),然后使用类似 sed 更改/etc/hosts .

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

这篇关于WSL2使用“本地主机"访问Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆