如何让 mDNS (avahi) 在适用于 Linux 的 Windows 子系统上工作?

And*_*eas 5 linux mdns windows-10 windows-subsystem-for-linux windows-10-v1709

我遵循了这个线程中的最后一个例子:

https://github.com/Microsoft/WSL/issues/384

换句话说:

~$ sudo service dbus start
 * Starting system message bus dbus                                                                                                                    [ OK ]
~$ sudo service avahi-daemon start
 * Starting Avahi mDNS/DNS-SD Daemon avahi-daemon                                                                                                      [ OK ]
~$ avahi-resolve --name rpi.local
Failed to resolve host name 'rpi.local': Timeout reached
Run Code Online (Sandbox Code Playgroud)

这是在安装此答案中列出的软件包后完成的。

rpi.localWindows 可以解决。

Windows 10 版本 10.0.16299 内部版本 16299

~$ lsb_release -a

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.3 LTS
Release:        16.04
Codename:       xenial
Run Code Online (Sandbox Code Playgroud)

Luc*_*VdV 0

不是解决方案,而是解决方法(对于 WSL2)。

这不仅仅是 MDNS 不起作用,真正的问题是 WSL2 在其自己的虚拟网络上 NAT 到您的物理网络,而 MDNS 无法通过。实际上在最新版本中可以使用,但仅适用于主机名称。我也曾经咒骂过这个。

我在 WSL 的 /etc/hosts 中包含了我经常需要的所有 mDNS 名称,并创建了此脚本以使用 Windows 名称解析来更新它们。

#!/bin/bash
grep -oP "[0-9.]*\s\K[A-Za-z0-9.-]+\.local" /etc/hosts | while read HOSTNAME
do
    echo -n "Pinging $HOSTNAME... "
    # Executing windows command without subshell breaks DO loop.
    IP=`echo "/mnt/c/Windows/System32/PING.EXE -4 -n 1 $HOSTNAME | grep -oP \"Reply from \K[0-9.-]+\"" | bash`
    echo $IP
    [ -z $IP ] || sudo sed -i "s/.*$HOSTNAME.*/$IP $HOSTNAME/" /etc/hosts
done

echo ====== Result in /etc/hosts
grep -P "[0-9.]*\s[A-Za-z0-9.-]+\.local" /etc/hosts
Run Code Online (Sandbox Code Playgroud)
  1. 直接在 WHILE 循环中执行 PING.EXE 对我来说打破了该循环,如果我不在子 shell 中执行它,它会在第一次迭代后停止。注释掉 IP= 行可以阻止该行为,因此肯定是该行打破了循环。我不知道这是由于执行 Windows 可执行文件引起的,还是由于将命令放在反引号之间而不是使用 $(command) 引起的,或者是其他我还没有想到的原因。
  2. 每个 IP/主机使用一根线路。一根线路上具有相同 IP 的两个名称将不起作用。
  3. 当然,不包含“*.local”名称的 /etc/hosts 行将保持不变:)
  4. 未回复的主机线路保持不变。
  5. sudo在该sed行中,因此您需要该权限来执行它。

-- 编辑:删除了 grep 命令中 - 和 oP 之间的空格