从 WSL2 内部访问在 Windows 中运行的本地主机?
我在我的 Windows 机器中运行本地 AEM 服务器.服务器在 localhost:4502 上运行.我正在使用在 WSL2 中运行的 Ubuntu 发行版进行开发.我想访问在我的 WSL2 Ubuntu 中的 Windows 机器上运行的 localhost:4502.
I am running a local AEM server in my Windows machine. The server is running on localhost:4502. I am using Ubuntu distro running in WSL2 for my development. I want to access the localhost:4502 running in the Windows machine in my WSL2 Ubuntu.
有没有办法做到这一点,或者不可能?
Is there any way to do that or is it not possible ?
我也在寻找一些解决方案来做到这一点,但目前没有这样的选项可用.查看此 GitHub 问题:
I was also looking for some solution to do this but currently, there is no such option available. Check out this GitHub issue:
https://github.com/microsoft/WSL/issues/4619
一种解决方案是:
如果您拥有 windows(host) 的 IP,那么它将完成这项工作,但唯一的问题是 IP 每次都会更改.但是,WSL2 将您的 Windows(主机)IP 存储在 /etc/resolv.conf
文件中.所以我们可以修改我们的 etc/hosts
来动态映射 winhost
到 IP.
If you have the IP of windows(host) then it will do the job but the only problem is that IP will change every time. But, WSL2 stores your windows(host) IP in /etc/resolv.conf
file. So we can modify our etc/hosts
to map winhost
to the IP dynamically.
在~/.bashrc
文件末尾添加以下几行.这将在启动 WSL 时 grep IP 并修改 etc/hosts
.
Add the following lines at the end of ~/.bashrc
file. This will grep the IP and modify the etc/hosts
when you boot the WSL.
export winhost=$(cat /etc/resolv.conf | grep nameserver | awk '{ print $2 }')
if [ ! -n "$(grep -P "[[:space:]]winhost" /etc/hosts)" ]; then
printf "%s\t%s\n" "$winhost" "winhost" | sudo tee -a "/etc/hosts"
fi
然后运行以下命令以重新加载更改.
then run the following command to reload the changes.
$ source ~/.bashrc
现在您可以在 WSL2(客户端)中使用 winhost
而不是 localhost
来访问运行 windows(主机)的服务器.在您的情况下,它将是 winhost:4502
但这将适用于任何其他用例以及访问在 Windows 等上运行的 Postgres/MySQL 服务器.
now you can use winhost
instead of localhost
in WSL2(client) to access the servers running windows(host). In your case, it will be winhost:4502
but this will work for any other use cases as well like accessing Postgres/MySQL server running on windows, etc.
注意:请始终记住在 Windows 上配置防火墙以允许这些端口,以便 WSL2 可以访问,否则您的连接可能会被防火墙阻止.
NOTE: Always remember to configure your firewall on windows to allow those ports so that WSL2 can access otherwise your connection may get blocked by firewall.