Skip to content

Instantly share code, notes, and snippets.

@rknell
Last active August 22, 2025 07:44
Show Gist options
  • Select an option

  • Save rknell/0a080a31064f4e5914d6aa2d1b21eed7 to your computer and use it in GitHub Desktop.

Select an option

Save rknell/0a080a31064f4e5914d6aa2d1b21eed7 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# To run just use:
# wget -qO- https://gist.githubusercontent.com/rknell/0a080a31064f4e5914d6aa2d1b21eed7/raw/c6e1c54159dcd0ae63c2e94ebceff224d60ad8e4/install-mdns-hosts-sync.sh | sudo bash
# Maintains a list of mDNS hosts in the hosts file so firefox on linux can even. Works on Fedora Kinoite and regular Fedora installs, probably works elsewhere... :shrug:
set -euo pipefail
if [[ ${EUID:-$(id -u)} -ne 0 ]]; then
echo "Please run as root (use sudo)."; exit 1
fi
install -d -m 0755 /etc/local/bin
cat >/etc/local/bin/mdns-hosts-sync.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
HOSTS_FILE="/etc/hosts"
TAG="# mdns-sync"
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT
# Remove all previously managed lines
awk -v tag="$TAG" '!index($0, tag)' "$HOSTS_FILE" >"$tmp"
# Enumerate all current .local hosts
avahi-browse -atlr 2>/dev/null | awk -F';' '
$1 == "=" && $4 ~ /\.local$/ {print $4}
' | sort -u | while read -r host; do
IP="$(avahi-resolve -n "$host" 2>/dev/null | awk "{print \$2}" || true)"
if [[ -n "${IP:-}" ]]; then
echo "$IP $host $TAG" >>"$tmp"
fi
done
# Replace only if changed
if ! cmp -s "$tmp" "$HOSTS_FILE"; then
install -m 0644 "$tmp" "$HOSTS_FILE"
fi
EOF
chmod +x /etc/local/bin/mdns-hosts-sync.sh
# Service
cat >/etc/systemd/system/mdns-hosts-sync.service <<'EOF'
[Unit]
Description=Sync /etc/hosts with all discovered .local mDNS hostnames
Wants=network-online.target avahi-daemon.service
After=network-online.target avahi-daemon.service
[Service]
Type=oneshot
ExecStart=/etc/local/bin/mdns-hosts-sync.sh
EOF
# Timer
cat >/etc/systemd/system/mdns-hosts-sync.timer <<'EOF'
[Unit]
Description=Run mDNS → /etc/hosts sync periodically
[Timer]
OnBootSec=15s
OnUnitActiveSec=60s
Persistent=true
[Install]
WantedBy=timers.target
EOF
# Enable & start
systemctl daemon-reload
systemctl enable --now mdns-hosts-sync.timer
systemctl start mdns-hosts-sync.service || true
echo "✅ Installed. Current managed entries:"
grep '# mdns-sync' /etc/hosts || true
# Helpful hints
command -v avahi-browse >/dev/null || {
echo "⚠️ 'avahi-browse' not found. Install avahi-tools."
if command -v rpm-ostree >/dev/null; then
echo " Kinoite: sudo rpm-ostree install avahi-tools && reboot"
else
echo " Fedora: sudo dnf install -y avahi-tools"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment