mdns

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package mdns provides generic Multicast DNS (mDNS) / DNS-SD primitives.

This package implements a minimal mDNS client capable of browsing for DNS-SD services, resolving service instances, and streaming service lifecycle events (added/removed/updated) from the local network. The DNS wire format it speaks is in the dnswire subpackage.

A Client is a querier only: it answers no queries and announces nothing. Of RFC 6762, it follows:

  • Section 5: one socket joined to 224.0.0.251, port 5353, shared by all of a client's operations; questions repeated after 1 s, then at doubling intervals, paced and merged across operations; records asked for again at 80% of their TTL while needed.
  • Section 6: responses only are acted on; records are taken from both the Answers and the Additional section.
  • Section 7.1: queries list the answers already known.
  • Section 10: records live for their TTL, in a cache shared by the client's operations; goodbyes (TTL=0) end them after a second; the cache-flush bit replaces a host's addresses; records our questions went unanswered for end after ten seconds (10.5).

Index

Constants

View Source
const ServicesMetaQuery = ServiceName("_services._dns-sd._udp")

ServicesMetaQuery is the well-known DNS-SD service used to enumerate all service types currently advertised on the network (RFC 6763 Section 9).

Variables

View Source
var ErrClientClosed = errors.New("mdns: client is closed")

ErrClientClosed is the error of a Browse, Discover or Watch that Close ended.

View Source
var ErrWatcherClosed = errors.New("mdns: watcher is closed")

ErrWatcherClosed is the error of a Watcher that Close stopped.

Functions

This section is empty.

Types

type ActionType

type ActionType int

ActionType describes a service-instance lifecycle change.

const (
	ActionAdded ActionType = iota
	ActionRemoved
	ActionUpdated
)

The lifecycle changes a Watcher reports.

func (ActionType) String

func (a ActionType) String() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an mDNS client for service discovery and watching.

It provides both one-shot discovery via Discover, and continuous event streaming via Watch. Browse and DiscoverServiceTypes expose the raw PTR answers underneath.

func New

func New(opts ...Option) *Client

New creates a new mDNS Client.

func (*Client) Browse

func (c *Client) Browse(ctx context.Context, service ServiceName) ([]DomainName, error)

Browse sends a PTR query for the given service and returns the names of the service instances found, each once (DNS names compare without regard to case), in the order they were first seen. It is the lowest-level discovery function: it does not resolve the instances.

It collects answers for the client's timeout (see WithTimeout) or until ctx is done, whichever comes first. If ctx ended first, the error is ctx.Err() and the names found until then are returned with it.

func (*Client) Close

func (c *Client) Close() error

Close closes the client's socket at once, rather than when it has been idle for a few seconds, and ends every Browse, Discover and Watch still in progress, with ErrClientClosed. The client stays usable: a later operation opens a new socket.

func (*Client) Discover

func (c *Client) Discover(ctx context.Context, service ServiceName) ([]ServiceInstance, error)

Discover performs a one-shot mDNS discovery for the given service type. It sends PTR queries, collects responses for the client's timeout (see WithTimeout) or until ctx is done, whichever comes first, and resolves each service instance into a ServiceInstance.

The error is ctx.Err() if ctx ended first, or the network error if the socket failed; the instances found until then are returned either way. When the timeout simply runs out, the error is nil.

This is a convenience wrapper around Watch that collects a snapshot and returns it.

func (*Client) DiscoverServiceTypes

func (c *Client) DiscoverServiceTypes(ctx context.Context) ([]ServiceName, error)

DiscoverServiceTypes queries the network for all service types advertised via DNS-SD (RFC 6763 Section 9) and returns each as a ServiceName ready to be queried for its instances.

Not every mDNS responder implements the meta-query; a device that only answers queries for its exact service type will not appear here even though a query for that type can still find it if the caller already knows the type.

Like Browse, it returns the types found so far along with ctx.Err() if ctx ends first.

func (*Client) DiscoverServiceTypesFunc

func (c *Client) DiscoverServiceTypesFunc(ctx context.Context, found func(ServiceName)) error

DiscoverServiceTypesFunc is DiscoverServiceTypes, calling found with each service type as soon as it is first seen, rather than returning them all once the query is over. That lets a caller start resolving the instances of a type while enumeration is still going. found is called on the calling goroutine, so it should not block for long.

func (*Client) IsDebug

func (c *Client) IsDebug() bool

IsDebug reports whether debug logging is enabled.

func (*Client) Timeout

func (c *Client) Timeout() time.Duration

Timeout returns the configured discovery timeout.

func (*Client) Watch

func (c *Client) Watch(ctx context.Context, service ServiceName, opts ...WatchOption) (*Watcher, error)

Watch starts watching the instances of a service type. It returns an error only if it cannot start, when the client cannot open its socket.

The watcher asks for instances of the service at once, and repeats the question, backing off; it asks for whatever records it lacks to resolve the instances it learns of. It emits Added events for new instances, Updated events for changed ones, and Removed events for those that have gone away (a goodbye, or nothing heard for a while).

The event channel is closed when ctx is done, Close is called, or the client's socket fails or is closed; Err then says which.

type DomainName

type DomainName = dnswire.DomainName

DomainName is a DNS name in dotted form, without the trailing dot, such as "Printer._ipp._tcp.local". It is dnswire's, here so that most programs need not import dnswire at all.

type Option

type Option func(*config)

Option configures a Client or Watcher.

func WithDebug

func WithDebug(debug bool) Option

WithDebug enables debug logging: the records of every response processed, every lifecycle event, and every question asked.

func WithLogger

func WithLogger(logger *log.Logger) Option

WithLogger sets the logger for diagnostic output.

func WithPacketHook

func WithPacketHook(hook func(Packet)) Option

WithPacketHook installs a function that is called with every datagram the client receives, before it is parsed, so that packets the client cannot parse are observed as well. All of a client's operations share one socket, so each datagram is observed once; the hook is called from the client's receive loop and should not block for long.

func WithQueryHook

func WithQueryHook(hook func(Query)) Option

WithQueryHook installs a function that is called with every query the client sends, so that its querying can be watched: when it asks, how often, and what. The hook is called from the client's querier, one query at a time, and should not block for long.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the discovery timeout (default: 5 seconds).

type Packet

type Packet struct {
	// Time is when the datagram was read from the socket.
	Time time.Time
	// Source is the address and port of the sender.
	Source netip.AddrPort
	// Data is the DNS message exactly as received. The hook owns it.
	Data []byte
}

Packet is one datagram received from the mDNS multicast group, as passed to the hook installed with WithPacketHook.

type Query

type Query struct {
	// Time is when the query was sent.
	Time time.Time
	// Questions are what it asked. The hook owns the slice.
	Questions []dnswire.Question
	// KnownAnswers is how many answers it listed as already known
	// (RFC 6762 Section 7.1).
	KnownAnswers int
}

Query is one query the client sent, as passed to the hook installed with WithQueryHook.

type RemovalReason

type RemovalReason int

RemovalReason says why a Watcher removed an instance.

const (
	// ReasonNone: the event is not a removal.
	ReasonNone RemovalReason = iota
	// ReasonGoodbye: the instance said it was going away (RFC 6762
	// Section 10.1).
	ReasonGoodbye
	// ReasonExpired: the instance's records ran out without being
	// received again.
	ReasonExpired
	// ReasonUnresponsive: nobody answered when the watcher asked about
	// the instance (RFC 6762 Section 10.5).
	ReasonUnresponsive
)

The reasons for removing an instance.

func (RemovalReason) String

func (r RemovalReason) String() string

type ServiceInstance

type ServiceInstance struct {
	// Instance is the service instance name, fully qualified as it
	// appears on the wire, e.g. "Foo-AB1234._foo._tcp.local".
	Instance DomainName
	// ServiceType is the service type, e.g. "_foo._tcp".
	ServiceType ServiceName
	// Port is the TCP/UDP port the service listens on.
	Port int
	// Target is the hostname the SRV record points to (before A/AAAA resolution).
	Target DomainName
	// Addrs are the addresses of the Target host: IPv4 before IPv6, each
	// in numerical order.
	Addrs []netip.Addr
	// TXT holds the TXT record's attributes as key/value pairs (RFC 6763
	// Section 6), parsed from the record's original length-prefixed
	// strings so that values containing spaces are preserved intact. A
	// valueless attribute (a boolean flag) is stored with an empty value.
	TXT map[string]string

	// Responder is who last sent the instance's SRV record, or, before
	// there is one, its PTR record. It is not necessarily the host the
	// instance runs on: an mDNS proxy, or a Thread border router, may
	// answer for it.
	Responder netip.AddrPort
	// LastSeen is when one of the instance's own records (PTR, SRV or
	// TXT) was last received.
	LastSeen time.Time
	// Expires is when the instance's PTR record runs out, unless it is
	// received again.
	Expires time.Time
}

ServiceInstance represents a resolved mDNS service instance.

type ServiceInstanceEvent

type ServiceInstanceEvent struct {
	Action    ActionType
	Instance  ServiceInstance
	Timestamp time.Time
	// Reason says why a removed instance was removed; it is ReasonNone
	// for other events.
	Reason RemovalReason
}

ServiceInstanceEvent is emitted by a Watcher when a service instance is added, removed, or updated.

type ServiceName

type ServiceName string

ServiceName is a DNS-SD service type such as "_ipp._tcp", or a subtype such as "_printer._sub._http._tcp" (RFC 6763 Section 7). MakeServiceName builds and checks one; a ServiceName written out directly is used as is.

func MakeServiceName

func MakeServiceName(service, proto string) (ServiceName, error)

MakeServiceName returns the service type of service over proto, such as "_ipp._tcp" for MakeServiceName("ipp", "tcp"). Both are given without the leading underscore, although one is accepted.

service must be a valid service name (RFC 6335 Section 5.1): 1 to 15 letters, digits and hyphens, at least one of them a letter, with no hyphen at either end or next to another. proto must be "tcp", or "udp" for every protocol other than TCP (RFC 6763 Section 7).

func (ServiceName) DomainName

func (s ServiceName) DomainName() DomainName

DomainName returns the fully-qualified DNS name for browsing.

func (ServiceName) String

func (s ServiceName) String() string

String returns the service name as a string.

type WatchOption

type WatchOption func(*Watcher)

WatchOption configures a Watcher.

func WithBufferSize

func WithBufferSize(size int) WatchOption

WithBufferSize sets the event channel buffer size (default: 100).

type Watcher

type Watcher struct {
	// contains filtered or unexported fields
}

Watcher streams the lifecycle events of the instances of one service type, as Client.Watch starts it.

It keeps track of known instances and emits Added, Updated and Removed events on its event channel. Events are dropped (and logged) when the channel buffer is full: the watcher does not block on slow consumers. The channel is the only way data leaves the watcher; higher-level code maintains its own state from the event stream.

The instances it has reported are owned by its receive loop goroutine, so they need no locking; the records it resolves them from are the client's (see recordCache).

func (*Watcher) Close

func (w *Watcher) Close()

Close stops the watcher and releases resources. It is safe to call multiple times.

func (*Watcher) Err

func (w *Watcher) Err() error

Err reports why the watcher stopped: ErrWatcherClosed after Close, the context's error if it ended, ErrClientClosed if the client was closed, or the error that broke the client's socket. It returns nil until the event channel is closed.

func (*Watcher) Events

func (w *Watcher) Events() <-chan ServiceInstanceEvent

Events returns the channel of the watcher's events. It is closed when the watcher stops.

Directories

Path Synopsis
Package dnswire reads and writes the DNS messages that Multicast DNS (RFC 6762) exchanges: names, records, and queries.
Package dnswire reads and writes the DNS messages that Multicast DNS (RFC 6762) exchanges: names, records, and queries.
internal
l10n
Package l10n provides the module's translation catalog and domain.
Package l10n provides the module's translation catalog and domain.
testutil
Package testutil provides small helpers shared by parser tests.
Package testutil provides small helpers shared by parser tests.
Package parsers provides DNS-SD service-type registries and TXT-record interpreters for the mDNS discovery tools in this project.
Package parsers provides DNS-SD service-type registries and TXT-record interpreters for the mDNS discovery tools in this project.
all
Package all registers every service parser family in this module.
Package all registers every service parser family in this module.
apple
Package apple provides service parsers for Apple protocols: AirPlay, AirPlay audio (RAOP), HomeKit Accessory Protocol (HAP), and Companion Link.
Package apple provides service parsers for Apple protocols: AirPlay, AirPlay audio (RAOP), HomeKit Accessory Protocol (HAP), and Companion Link.
ikea
Package ikea provides service parsers for the IKEA Dirigera / Home Smart ecosystem: the main hub API (_dirigera._tcp), its internal control-plane protocol (_ihsp._tcp), and heartbeat/status advertisement (_ihsh._udp).
Package ikea provides service parsers for the IKEA Dirigera / Home Smart ecosystem: the main hub API (_dirigera._tcp), its internal control-plane protocol (_ihsp._tcp), and heartbeat/status advertisement (_ihsh._udp).
media
Package media provides service parsers for streaming and media protocols (Google Cast, Spotify Connect).
Package media provides service parsers for streaming and media protocols (Google Cast, Spotify Connect).
nearby
Package nearby provides service parsers for Google's Nearby Presence and Quick Share over the local network.
Package nearby provides service parsers for Google's Nearby Presence and Quick Share over the local network.
printers
Package printers provides service parsers for network printing and scanning protocols (AirPrint / Bonjour IPP, LPD, eSCL scanners).
Package printers provides service parsers for network printing and scanning protocols (AirPrint / Bonjour IPP, LPD, eSCL scanners).
samsung
Package samsung provides service parsers for Samsung SmartThings.
Package samsung provides service parsers for Samsung SmartThings.
thread
Package thread provides service parsers for the Thread/Matter ecosystem: meshcop (Thread Border Agent commissioning), TREL, and Matter operational, commissionable node and commissioner discovery.
Package thread provides service parsers for the Thread/Matter ecosystem: meshcop (Thread Border Agent commissioning), TREL, and Matter operational, commissionable node and commissioner discovery.
vnc
Package vnc provides service parsers for VNC, the Remote Framebuffer protocol (RFC 6143): servers that offer their screen, and viewers that wait for a server to connect to them.
Package vnc provides service parsers for VNC, the Remote Framebuffer protocol (RFC 6143): servers that offer their screen, and viewers that wait for a server to connect to them.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL