Avahi
Avahi is a free Zero-configuration networking (zeroconf) implementation, including a system for multicast DNS/DNS-SD service discovery. It allows programs to publish and discover services and hosts running on a local network with no specific configuration. For example you can plug into a network and instantly find printers to print to, files to look at and people to talk to. It is licensed under the GNU Lesser General Public License (LGPL).
Installation
You can manage the Avahi daemon with avahi-daemon.service using systemd.
Using Avahi
Hostname resolution
Avahi provides local hostname resolution using a «hostname.local» naming scheme. To enable it, install the nss-mdns package and start/enable avahi-daemon.service .
Then, edit the file /etc/nsswitch.conf and change the hosts line to include mdns_minimal [NOTFOUND=return] before resolve and dns :
- If you experience slowdowns in resolving .local hosts (or you do not want to use IPv6) try to use mdns4_minimal and mdns4 instead of mdns_minimal and mdns respectively.
- The line above makes nss-mdns authoritative for the .local domain, unless your unicast DNS server responds to SOA queries for the top level local name, or if the request has more than two labels. See nss-mdns activation notes.
-
responds to these queries even if its mDNS support is disabled. See #systemd-resolved prevents nss-mdns from working.
- More info about nss configuration can be found on nss-mymachines(8) and in Avahi docs.
Configuring mDNS for custom TLD
The mdns_minimal module handles queries for the .local TLD only. Note the [NOTFOUND=return] , which specifies that if mdns_minimal cannot find *.local , it will not continue to search for it in dns , myhostname , etc.
In case you want Avahi to support other TLDs, you should:
- replace mdns_minimal [NOTFOUND=return] with the full mdns module. There also are IPv4-only and IPv6-only modules mdns[46](_minimal)
- customize /etc/avahi/avahi-daemon.conf with the domain-name of your choice
- whitelist Avahi custom TLDs in /etc/mdns.allow
Tools
Avahi includes several utilities which help you discover the services running on a network. For example, run
to discover services in your network.
The Avahi Zeroconf Browser ( avahi-discover – note that it needs Avahi’s optional dependencies gtk3 , dbus-python and python-gobject ) shows the various services on your network. You can also browse SSH and VNC Servers using bssh and bvnc respectively.
Firewall
Be sure to open UDP port 5353 if you are using a firewall.
Link-Local (Bonjour/Zeroconf) chat
Avahi can be used for Bonjour protocol support under Linux. Check Wikipedia:Comparison of instant messaging clients or List of applications#Instant messaging clients for a list of clients supporting the Bonjour protocol.
Obtaining IPv4LL IP address
alt=»Merge-arrows-2.png» width=»48″ height=»48″ />This article or section is a candidate for merging with dhcpcd. alt=»Merge-arrows-2.png» width=»48″ height=»48″ />
The dhcpcd client can attempt to obtain an IPv4LL address if it failed to get one via DHCP. By default this option is disabled. To enable it, comment noipv4ll string:
Alternatively, run avahi-autoipd :
Adding services
Avahi advertises the services whose *.service files are found in /etc/avahi/services . Files in this directory must be readable by the avahi user/group.
If you want to advertise a service for which there is no *.service file, it is very easy to create your own. As an example, let us say you wanted to advertise a quote of the day (QOTD) service operating per RFC:865 on TCP port 17 which you are running on your machine
The first thing to do is to determine the <type> . avahi.service(5) indicates that the type should be «the DNS-SD service type for this service. e.g. ‘_http._tcp'». Since the DNS-SD register was merged into the IANA register in 2010, we look for the service name on the IANA register or in /etc/services file. The service name shown there is qotd . Since we are running QOTD on tcp, we now know the service is _qotd._tcp and the port (per IANA and RFC 865) is 17 .
Our service file is thus:
For more complicated scenarios, such as advertising services running on a different server, DNS sub-types and so on, consult avahi.service(5) .
Keep in mind that Avahi does not support arbitrary strings in the <type> field, you can only set values known in service database of Avahi. If you want to register something custom you will likely have to edit the database definition, build an updated version and distribute it to your hosts.
Avahi comes with an example service file to advertise an SSH server. To enable it:
File sharing
If you have an NFS share set up, you can use Avahi to be able to automount them in Zeroconf-enabled browsers (such as Konqueror on KDE and Finder on macOS) or file managers such as GNOME/Files.
Create a .service file in /etc/avahi/services with the following contents:
The port is correct if you have insecure as an option in your /etc/exports ; otherwise, it needs to be changed (note that insecure is needed for macOS clients). The path is the path to your export, or a subdirectory of it. For some reason the automount functionality has been removed from Leopard, however a script is available. This was based upon this post.
Samba
With the Avahi daemon running on both the server and client, the file manager on the client should automatically find the server.
Vsftpd
You can also auto-discover regular FTP servers, such as vsftpd. Install the vsftpd package and change the settings of vsftpd according to your own personal preferences (see this thread on ubuntuforums.org or vsftpd.conf(5) ).
Create a .service file in /etc/avahi/services with the following contents:
The FTP server should now be advertised by Avahi. You should now be able to find the FTP server from a file manager on another computer in your network. You might need to enable #Hostname resolution on the client.
Troubleshooting
Hostname changes with appending incrementing numbers
This is a known bug that is caused by a hostname race condition. One possible workaround is disabling IPv6 to attempt to prevent the race condition. If multiple interfaces are present use allow-interfaces to limit Avahi to a single interface. Another possible workaround is to disable the cache to prevent Avahi from checking for host name conflicts altogether, but this prevents Avahi from performing lookups.
systemd-resolved prevents nss-mdns from working
nss-mdns only works if the DNS server listed in /etc/resolv.conf returns NXDOMAIN to SOA queries for the «local» domain.[1]
Check if your configured DNS server answers the SOA query for the «local» domain with NXDOMAIN first. For example:
If the DNS server responds with NXDOMAIN , you do not need to follow the steps below. Avahi should be able to find resources in the network normally, even if using systemd-resolved.
Что такое Zeroconf и с чем его едят
Я, как старый линуксоид, когда впервые установил Ubuntu и увидел незнакомое слово avahi, конечно же сразу посмотрел в google. Потыкался в несколько ссылок, увидел другие непонятные слова, типа zeroconf, multicast dns, bonjour. Сразу понял, что это какая то мутная технология от Apple и нафиг мне ненужная.
Однако, с ростом локальной сети внутри моей квартиры, подумал, что неплохо бы было полюбопытствовать, как можно приспособить zeroconf, чтобы облегчить себе жизнь.
-
— это протокол, разработанный Apple и призванный решать следующие проблемы:
- выбор сетевого адреса для устройства;
- нахождение компьютеров по имени;
- обнаружение сервисов, например принтеров.
— открытая и свободная реализация протокола zeroconf. — open-source реализация протокола zeroconf от Apple.
Для разрешения имен (name resolving) используется протокол Multicast DNS или сокращено mDNS. Он позволяет устройству выбрать имя в зоне .local. Работает это почти как обычный DNS, но с нюансами. Каждый компьютер хранит записи своей зоны ( A , MX , SRV ) сам и сам же обслуживает запросы к ним. Когда какой либо компьютер хочет узнать запись зоны, скажем определить IP-адрес по имени (получить запись A для заданной зоны), он обращается по multicast-адресу 224.0.0.251 . Соответственно, запрос получают все компьютеры в локальной сети, а отвечает тот, кто хранит зону для интересующего нас имени.
Для поиска и обнаружения сервисов используется протокол DNS based Service Discovery или DNS-SD. Для того, чтобы прорекламировать, какие сервисы доступны на устройстве, используются DNS-записи типа SRV , TXT , PTR .
- Поставить пакеты avahi-daemon , avahi-autoipd , libnss-mdns . Если у вас стоит Ubuntu, то скорее всего эти пакеты уже установлены.
- Включить IPv4LL. Этот шаг совершенно не обязателен. Если у вас есть любой IP-адрес, который нормально маршрутизируется в локальной сети, то использовать IPv4LL не нужно и даже вредно, так как по стандарту, маршрутизатуры не должны форвардить пакеты с link-local адресами ( 169.254.* ). Иными словами, пробросить интернет через NAT скорее всего не удастся (мне не удалось). Но если вы уж решились, то достаточно для сетевого интерфейса локальной сети, в файле /etc/network/interfaces поставить тип ipv4ll . Что-то типа такого:
Welcome to Avahi
Avahi is a system which facilitates service discovery on a local network via the mDNS/DNS-SD protocol suite. This enables you to plug your laptop or computer into a network and instantly be able to view other people who you can chat with, find printers to print to or find files being shared. Compatible technology is found in Apple MacOS X (branded «Bonjour» and sometimes «Zeroconf»).
Avahi is primarily targetted at Linux systems and ships by default in most distributions. It is not ported to Windows at this stage, but will run on many other BSD-like systems. The primary API is D-Bus and is required for usage of most of Avahi, however services can be published using an XML service definition placed in /etc/avahi/services.
See also the nss-mdns project, which allows hostname lookup of *.local hostnames via mDNS in all system programs using nsswitch
Avahi linux что это такое
An account of the Avahi (zeroconf, Apple Bonjour) framework provided by Debian. Based on the packages distributed with Debian 10 (buster) and Debian 11 (bullseye).
- Introduction
- Avahi Utilities
- Hostname Resolution
- Using avahi-browse
- Debian Package Integration with Avahi
- Disabling avahi-daemon
- Registering a New Service in Avahi
- Printing and Scanning Services
Introduction
- publish services and hosts running on a local network, and
- discover services and hosts running on a local network.
The local network is assumed to be trusted. A firewall should should permit multicast traffic on port 5353. Installation of Avahi is straightforward and generally maintenance-free afterwards.
Machines that have cups installed will already have avahi-daemon as a recommended package.
Avahi Utilities
Basically, avahi-daemon will quietly get on with its job of publishing and discovering network services and hosts and most users will require little more from it apart from hostname resolution.
Hostname Resolution
Hostname resolution via the system’s Name Server Switch (NSS) facility is performed by libnss-mdns, which is recommended by avahi-daemon. Otherwise do
As explained in /usr/share/doc/libnss-mdns/README.Debian, the package’s post-installation script alters a line in /etc/nsswitch.conf to read
The mDNS domain .local is where hosts on the network reside and mdns4_minimal handles queries only for that domain. Hostname resolution takes place automatically with commands such as
To resolve a hostname to an IPv4 address with avahi-resolve:
The reverse process is performed with
avahi-resolve obtains an IP address or hostname directly from the mDNS multicast from hosts. It does not use the NSS functionality of libnss-mdns.
Using avahi-browse
For a complete view of services and hosts on the network:
An entry from the output of one such command will be used to illustrate the common features of any entry.
Music Player Daemon is the friendly service name. The service is running on port 6600 of the machine desktop.local with an IPv4 address 192.168.7.20. The text record (txt =) in this case is empty. If a service name is not available it will be replaced by the service type. All this information is published and will be available to a client wishing to access the service.
A list of all the service names known to avahi-daemon is given by
gives a list of matching service types, application protocol names. The service type _mpd._tcp matches the human-readable Music Player Daemon. This service can specifically be browsed for with
Display service types of services discovered on the network:
Debian Package Integration with Avahi
Some indication of the Debian packages that support service publication and discovery may be gleaned from libavahi-client3: