mDNS
Multicast DNS
A protocol for discovering devices on a local network via .local domains without a DNS server. Implemented by Apple Bonjour and Linux Avahi, it is used for automatic IoT device discovery and zero-config networking.
Multicast DNS
A protocol for discovering devices on a local network via .local domains without a DNS server. Implemented by Apple Bonjour and Linux Avahi, it is used for automatic IoT device discovery and zero-config networking.
mDNS (Multicast DNS) is a zero-configuration networking protocol that allows host names to be resolved to IP addresses on a local network without a DNS server. Regular DNS queries a central server, but mDNS broadcasts queries to all devices on the local network using multicast.
mDNS was first implemented by Apple in 2002 as Bonjour (formerly Rendezvous). It was later standardized as RFC 6762, and on Linux it is implemented by the Avahi daemon. It has been supported by default since Windows 10. mDNS mainly uses the .local domain, so you can access devices by names such as MacBook.local or raspberrypi.local.
mDNS uses UDP port 5353 and sends queries to the multicast address 224.0.0.251 (IPv4) or ff02::fb (IPv6). Of the devices that receive the request, only the device with the matching name responds. This approach is particularly useful in small networks that have no DHCP server or DNS server.
In practice, mDNS is widely used for automatic printer discovery, AirPlay/Chromecast streaming, IoT device setup, and access to local servers in development environments. Combined with DNS-SD (DNS Service Discovery), it can automatically discover the services available on the network (printers, file sharing, web servers, etc.).
from zeroconf import ServiceBrowser, Zeroconf, ServiceInfo
import socket
import time
# pip install zeroconf
# 1. mDNS 서비스 검색 (예: HTTP 서버 찾기)
class MyListener:
def add_service(self, zc, type_, name):
info = zc.get_service_info(type_, name)
if info:
addresses = [socket.inet_ntoa(addr) for addr in info.addresses]
print(f"발견: {name}")
print(f" 주소: {addresses}")
print(f" 포트: {info.port}")
print(f" 속성: {info.properties}")
def remove_service(self, zc, type_, name):
print(f"제거됨: {name}")
def update_service(self, zc, type_, name):
print(f"업데이트: {name}")
# HTTP 서비스 검색 시작
zeroconf = Zeroconf()
browser = ServiceBrowser(zeroconf, "_http._tcp.local.", MyListener())
print("서비스 검색 중... (10초)")
time.sleep(10)
zeroconf.close()
# 2. mDNS 서비스 등록 (자신의 서비스 광고)
from zeroconf import ServiceInfo, Zeroconf
import socket
def register_service():
zc = Zeroconf()
# 웹서버 서비스 정보
info = ServiceInfo(
"_http._tcp.local.", # 서비스 타입
"My Web Server._http._tcp.local.", # 서비스 이름
addresses=[socket.inet_aton("192.168.1.100")],
port=8080,
properties={"path": "/api/", "version": "1.0"}
)
zc.register_service(info)
print("서비스 등록 완료: my-web-server.local:8080")
input("엔터를 누르면 서비스 해제...")
zc.unregister_service(info)
zc.close()
# 3. .local 도메인 직접 해석
import socket
try:
ip = socket.gethostbyname("raspberrypi.local")
print(f"raspberrypi.local → {ip}")
except socket.gaierror:
print("mDNS 해석 실패 - Avahi/Bonjour 확인 필요")
# === macOS (Bonjour) ===
# .local 도메인 해석
ping raspberrypi.local
ssh pi@raspberrypi.local
# 네트워크 서비스 검색
dns-sd -B _http._tcp # HTTP 서버 찾기
dns-sd -B _printer._tcp # 프린터 찾기
dns-sd -B _airplay._tcp # AirPlay 장치 찾기
dns-sd -B _googlecast._tcp # Chromecast 찾기
dns-sd -B _services._dns-sd._udp # 모든 서비스 타입
# 특정 서비스 상세 정보
dns-sd -L "My Printer" _printer._tcp
# mDNS 쿼리
dns-sd -Q raspberrypi.local A # A 레코드 (IPv4)
dns-sd -Q raspberrypi.local AAAA # AAAA 레코드 (IPv6)
# === Linux (Avahi) ===
# Avahi 설치
sudo apt install avahi-daemon avahi-utils
# .local 해석
avahi-resolve -n raspberrypi.local
avahi-resolve -a 192.168.1.100 # 역방향 해석
# 서비스 검색
avahi-browse -a # 모든 서비스
avahi-browse -t _http._tcp # HTTP 서버
avahi-browse -r _ssh._tcp # SSH 서버 (상세정보)
# 자신의 서비스 광고
avahi-publish -s "My Server" _http._tcp 8080 "path=/api"
# mDNS 상태 확인
systemctl status avahi-daemon
# === Windows 10+ ===
# mDNS 해석 (기본 지원)
ping raspberrypi.local
# Bonjour SDK 설치 후 dns-sd 사용 가능
dns-sd -B _http._tcp local
# 방화벽에서 mDNS 허용 (UDP 5353)
netsh advfirewall firewall add rule name="mDNS" dir=in action=allow protocol=UDP localport=5353
// npm install bonjour-service (Node.js)
const Bonjour = require('bonjour-service').default;
const bonjour = new Bonjour();
// 1. HTTP 서비스 검색
console.log('로컬 네트워크에서 HTTP 서버 검색 중...\n');
const browser = bonjour.find({ type: 'http' }, (service) => {
console.log('발견된 서비스:');
console.log(` 이름: ${service.name}`);
console.log(` 호스트: ${service.host}`);
console.log(` 포트: ${service.port}`);
console.log(` 주소: ${service.addresses}`);
console.log(` TXT: ${JSON.stringify(service.txt)}`);
console.log('---');
});
// 2. 자신의 서비스 광고 (등록)
const service = bonjour.publish({
name: 'My Node.js API Server',
type: 'http',
port: 3000,
txt: {
version: '1.0.0',
path: '/api/v1',
secure: 'false'
}
});
console.log('서비스 등록됨: my-nodejs-api.local:3000');
// 서비스 타입별 검색 예제
function searchServices(type, description) {
bonjour.find({ type }, (service) => {
console.log(`[${description}] ${service.name} at ${service.host}:${service.port}`);
});
}
// 다양한 서비스 검색
searchServices('http', 'Web Server');
searchServices('printer', 'Printer');
searchServices('ssh', 'SSH Server');
searchServices('ftp', 'FTP Server');
searchServices('airplay', 'AirPlay');
searchServices('googlecast', 'Chromecast');
// 3. mDNS 직접 쿼리 (dns 모듈)
const dns = require('dns');
// .local 도메인 해석 (mDNS 지원 시스템에서 동작)
dns.lookup('raspberrypi.local', (err, address) => {
if (err) {
console.log('mDNS 해석 실패:', err.message);
} else {
console.log(`raspberrypi.local → ${address}`);
}
});
// 종료 처리
process.on('SIGINT', () => {
service.stop(() => {
bonjour.destroy();
console.log('\n서비스 해제 및 종료');
process.exit();
});
});
"For device discovery in the smart home app, you can use mDNS-based service discovery. Each device advertises its service as _myiot._tcp.local, and the app discovers it automatically by browsing. Users don't need to enter IP addresses manually."
"If a printer can't be discovered, first check the mDNS traffic. UDP port 5353 may be blocked by the firewall. If the network is separated by VLANs, you need to configure an mDNS reflector or Avahi reflector for devices to be visible on other subnets as well."
"When setting up a Raspberry Pi, just enabling avahi-daemon lets you SSH directly to raspberrypi.local. You don't need to log into the router to find the IP address. To change the name, just edit /etc/hostname and /etc/hosts."
Because mDNS is multicast-based, it works only within the same subnet. To discover devices on a different VLAN, you need to configure an mDNS gateway or an Avahi reflector.
In enterprise networks and cloud environments, the mDNS port is often blocked. If .local domains cannot be resolved during local development, check your firewall settings.
mDNS is for local networks only. In production, be sure to use static DNS or a service registry (Consul, etcd). .local domains cannot be resolved on the internet.
Use it for convenience in development/test environments, and use it for local device discovery in IoT/smart home apps. First check that Avahi (Linux) or Bonjour (macOS) is working properly.