lanbcast

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 14 Imported by: 1

README

lanbcast

Sends a LAN discovery probe to the limited broadcast address, to the directed broadcast address of every LAN interface and, if asked, to the IPv6 all-nodes group on every LAN interface, and collects the answers, in Go.

Go Reference test Go

A host with a VPN or several interfaces may route 255.255.255.255 somewhere it cannot be sent (macOS answers "can't assign requested address" while a VPN tunnel holds that route), or through one interface only. The directed broadcast addresses (for example 192.168.0.255) still reach each LAN, and a socket bound to one interface sends the limited broadcast out of that interface. Standard library only, no cgo.

Features

Behaviour Status
Send to 255.255.255.255 and to the directed broadcast address of each interface that is up and can broadcast (WriteBroadcast, Send) Implemented
Skip loopback and point-to-point (VPN) interfaces, and /31 and /32 networks Implemented
Skip VPN, tunnel and peer-to-peer radio interfaces by name (TunnelNames: utun, tun, tap, wg, ppp, ipsec, gif, stf, zt, tailscale, awdl, llw) Implemented in Send, Probe and ProbeConn, overridable; WriteBroadcast keeps its v0.1 choice
Choose interfaces by name pattern, exclusion pattern or predicate (Options) Implemented
IPv6: send to ff02::1 (or any ff02::/16 group) once per interface, zone set to the interface name Implemented, opt-in: Send with an IPv6 socket, or ProbeOptions.IPv6
Send the probe and read the answers on the same socket until a context ends (Probe, ProbeConn, Collect) Implemented
Drop the duplicate answer of a device that heard both the limited and a directed broadcast Implemented, on by default (KeepDuplicates turns it off)
Resend the probe while waiting Implemented (Resends, ResendInterval)
Send the limited broadcast out of every LAN interface, not only the one the routing table picks Implemented, opt-in (ProbeOptions.PerInterface): tested on macOS and on Linux (three LANs in network namespaces); Windows only on a one-adapter CI runner
Name the interface an answer came in on Implemented: exact from the kernel on Linux and macOS (tested) and Windows (written from the Windows headers; first run by the workflow's windows-latest job) (InterfaceExact); elsewhere exact for per-interface sockets and IPv6 link-local senders, inferred from the subnet for other IPv4 senders
Answer probes: the device side (Responder, Request) Implemented: every interface or a chosen set, IPv4 and IPv6, arrival interface, reply to the sender
Send any other destination alone Implemented
Succeed when at least one send succeeded; otherwise return the first error Implemented

WriteBroadcast is unchanged from v0.1: same signature, same interfaces, same sends. A device that hears both the limited and a directed broadcast answers twice; with WriteBroadcast the caller keys answers by device, Probe and ProbeConn drop identical copies.

IPv6 is opt-in because most devices that answer vendor broadcast probes (WiZ, Xiaomi miIO, TP-Link Kasa, EtherNet/IP adapters) speak IPv4 only. ff02::1 reaches every IPv6 node on the link, so a device that listens on the probe's port over IPv6 hears it the way an IPv4 device hears a broadcast.

Choosing how to send a discovery broadcast

The plain-net and x/net rows of this comparison were read from source in October 2026 (Go 1.27.1, golang.org/x/net v0.61.0); the Go socket options below were also checked in Go 1.26.2. Check the projects themselves before relying on a row.

this module net.ListenPacket and WriteTo 255.255.255.255 golang.org/x/net/ipv4 PacketConn schollz/peerdiscovery v1.7.6 lowbit-dev/beacon (2026-05-11 commit)
What it is send functions over any net.PacketConn, a probe helper that also reads the answers, and a responder for the device side the standard library (Go sets SO_BROADCAST on IPv4 UDP sockets) per-packet control messages: choose the outgoing interface (Linux, macOS), read the arrival interface discovery between peers running the same library, by multicast send one probe to one address, return the first answer
Reaches the LAN while a VPN holds the 255.255.255.255 route yes, through each LAN's directed broadcast, and with PerInterface through a socket bound to each LAN no only through code you write: it does not find interfaces or addresses not applicable (multicast group 239.255.255.250) no
Finds each interface's directed broadcast address yes; skips loopback, point-to-point, tunnel names, /31 and /32 no no no no
IPv6 ff02::/16 per interface, opt-in by hand, one zone at a time through golang.org/x/net/ipv6 yes (ff02::c by default) no
Collects answers all of them until a context ends, duplicates dropped by hand by hand yes, from peers the first only
Answers probes (the device side) Responder: every interface, arrival interface, reply to the sender by hand by hand yes, each peer is both no
Arrival interface exact from the kernel's packet information on Linux, macOS and Windows; elsewhere from the binding, the zone or the subnet no exact, from control messages (Linux, macOS) no no
Works with devices that answer a vendor broadcast probe (WiZ, miIO, TP-Link, EtherNet/IP) yes yes, on a host without that VPN route yes no, both ends must run it yes, one answer only; it sends from a dual-stack "udp" socket, which on Windows gets no SO_BROADCAST from Go
Dependencies none none golang.org/x/net (with x/sys) golang.org/x/net none

Pick this module when your program sends a vendor's discovery probe and must work on laptops and gateways with VPNs or several interfaces, or when it plays the device and must answer such probes (Responder). Use plain net when the host has one LAN and no VPN. Use x/net/ipv4 for other per-packet control (TTL, source address, multicast loopback), and peerdiscovery when every node runs your own Go program.

Operating system notes

  • Socket options (all platforms). Go turns on SO_BROADCAST for every UDP socket on Linux, macOS and the BSDs, AIX and Solaris (net/sockopt_*.go). On Windows it does so only when the socket is not IPv6 (net/sockopt_windows.go), and net.ListenPacket("udp", ...) is a dual-stack IPv6 socket there. Use "udp4" for broadcasts; Probe does.
  • Limited broadcast, one interface. Without PerInterface, 255.255.255.255 leaves through the one interface the routing table picks, on every system. The directed broadcasts cover the other LANs, but a device with no address in the LAN's subnet (factory default, setup mode, a static address from another site) hears only the limited broadcast.
  • PerInterface on Linux. Each socket is bound to the interface's IPv4 address. Linux sends a limited broadcast through the interface that owns the source address (net/ipv4/route.c, ip_route_output_key_hash_rcu), so SO_BINDTODEVICE and its privilege are not needed. Tested with three LANs built from network namespaces and veth pairs and a dummy interface holding the 255.255.255.255 route (as a VPN does), in a privileged container (TestNetnsMultiLAN, testdata/netns, and the workflow's netns job): without PerInterface only the directed broadcasts reach the LANs, so a device with no address in its LAN's subnet is missed; with it, every device answers, each answer named with its exact interface.
  • PerInterface on macOS. The socket is bound to the address and to the interface with IP_BOUND_IF. Tested on macOS 26 (en0, with Apple's peer-to-peer and VPN interfaces present).
  • PerInterface on Windows and the BSDs. Only the address binding is done. Windows is widely reported to send a limited broadcast through the interface of the bound address. The workflow runs the tests on a windows-latest runner (one adapter, so it checks the code paths and the packet-information parsing over loopback, not several LANs); the BSDs are only compiled.
  • Arrival interface. On Linux (IP_PKTINFO, IPV6_RECVPKTINFO), macOS (IP_RECVPKTINFO, IPV6_RECVPKTINFO) and Windows (IP_PKTINFO and IPV6_PKTINFO through WSARecvMsg; not yet run when v0.3.0 was cut, the workflow's Windows job is its first run) every socket asks the kernel for each datagram's interface index, so Answer.Interface and Request.Interface are exact (InterfaceExact) even on one shared socket. Elsewhere they fall back to the socket's binding, the IPv6 zone or the subnet, as in v0.2. ProbeConn turns the option on for the caller's socket too; it only adds control messages, which ReadFrom ignores.
  • Answers sent by broadcast. A socket bound to a unicast address does not receive broadcasts. A device that answers by broadcast rather than to the sender is heard by the default single socket, not by PerInterface sockets.
  • Interface flags on Windows. Go derives them from the adapter type: Ethernet, Wi-Fi, token ring and IEEE 1394 can broadcast; PPP and tunnel adapters are point-to-point; other types (many VPN drivers present as "proprietary virtual") have neither flag, so both the IPv4 and IPv6 paths skip them. OpenVPN's TAP-Windows adapter presents as Ethernet, and Windows names are the user's friendly names ("Ethernet 2"), so the tunnel name list rarely matches there: use Options.Exclude or Options.Filter. Name patterns are compared without regard to case.
  • IPv6 zones. The zone of each ff02::/16 destination is the interface name, which Go resolves to an index on every platform, Windows friendly names included. An interface needs an IPv6 link-local address and the multicast flag to be used.
  • Apple interfaces. awdl0 and llw0 (peer-to-peer Wi-Fi) are up, can broadcast and have IPv6 link-local addresses, so without the name list they would receive the IPv6 probe; they are on the tunnel list.

Install

go get github.com/cB-Sigma/lanbcast@latest

Requires Go 1.22 or later.

Quick start

Probe and collect, from ExampleProbe:

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
opts := &lanbcast.ProbeOptions{PerInterface: true, IPv6: true, Resends: 1}
err := lanbcast.Probe(ctx, []byte(`{"method":"getPilot","params":{}}`), 38899, opts, func(a lanbcast.Answer) {
	fmt.Println(a.From, a.Interface, string(a.Data))
})

On your own socket, from ExampleWriteBroadcast:

conn, err := net.ListenPacket("udp4", ":0")
if err != nil {
	return err
}
defer conn.Close()
probe := []byte(`{"method":"getPilot","params":{}}`)
err = lanbcast.WriteBroadcast(conn, probe, &net.UDPAddr{IP: net.IPv4bcast, Port: 38899})

Read the answers from conn as usual, or use ProbeConn to send and read in one call.

The device side, answering probes (as a simulator or emulated device does; ExampleResponder runs the same over loopback):

r, err := lanbcast.NewResponder(38899, nil)
if err != nil {
	return err
}
defer r.Close()
err = r.Serve(ctx, func(q lanbcast.Request) []byte {
	log.Printf("probe from %s on %s", q.From, q.Interface)
	return []byte(`{"method":"getPilot","result":{"mac":"a8bb50000001"}}`)
})

Documentation

Reference: pkg.go.dev/github.com/cB-Sigma/lanbcast.

Name Contents
WriteBroadcast v0.1 send: limited broadcast plus each LAN's directed broadcast
Send the same with Options, plus per-interface ff02::/16 multicast
Destinations the addresses Send would use
Options interface choice: Interfaces, Exclude, AllowTunnels, Filter
TunnelNames the default excluded name patterns
Probe opens sockets, sends, passes answers to a callback until the context ends
ProbeConn the same on the caller's socket
Collect Probe returning a slice
ProbeOptions KeepDuplicates, Resends, ResendInterval, BufferSize, LocalPort, IPv6, PerInterface
Answer sender, bytes, interface, InterfaceExact
Responder, NewResponder the device side: answer probes on a port, on every interface or a chosen set (RespondOptions)
Request a probe the responder received: sender, bytes, interface

Testing

go test -race ./...

The tests use made-up interface tables, a fake net.PacketConn, loopback sockets, and this host's real interfaces (TestProbeOnHost, skipped with -short; each part logs instead of failing when the host does not deliver its own broadcasts or multicasts back to itself). // Covers: SIG-... comments in tests are requirement IDs of the SigmaM2M project's compliance report and have no meaning outside it.

TestResponderLoopback probes a Responder over loopback and checks that both ends get the exact arrival interface from the kernel, which exercises each system's packet-information parsing. TestNetnsMultiLAN (Linux, root, SIGMA_NETNS=1) builds three LANs with network namespaces and veth pairs, one of them holding a device with no address in its subnet, and a dummy interface holding the 255.255.255.255 route as a VPN does, then probes Responders in the namespaces with and without PerInterface and over IPv6:

docker build -t sigma-lanbcast-netns testdata/netns
docker run --rm --privileged -v "$PWD":/src sigma-lanbcast-netns

The GitHub workflow runs the tests on Linux, macOS and Windows runners, and the namespace test as root on Linux.

Interop tested against

No other implementation to compare with: the module chooses addresses, sends and reads, and its responder answers its own prober in the tests. The libraries that use it are tested against their devices or simulators.

  • github.com/cB-Sigma/wiz uses it for WiZ light discovery.
  • SigmaM2M's EtherNet/IP, Xiaomi miIO and TP-Link libraries use it for their discovery broadcasts.

This module has no simulator; Responder is what simulators of discovery-probed devices can build on.

Status

v0.x. The API may change before v1. See CHANGELOG.md.

Contributing

See CONTRIBUTING.md.

Security

See SECURITY.md for how to report a vulnerability.

Licence

Apache-2.0 (see LICENSE and NOTICE). Copyright 2026 Abhinav Gautam.

Documentation

Overview

Package lanbcast sends LAN discovery datagrams to the limited broadcast address and to the directed broadcast address of every LAN interface, and optionally to the IPv6 all-nodes link-local multicast group on every LAN interface.

WriteBroadcast is the original function and keeps its behaviour. Send does the same with Options: interfaces chosen by name pattern or predicate, VPN and tunnel interfaces skipped by default, and link-local IPv6 multicast (ff02::1 and the rest of ff02::/16) sent once per interface. Destinations lists the addresses either would send to.

Probe and ProbeConn send a probe and pass the answers that arrive on the same socket to a callback until a context ends, dropping the duplicate answers a device sends when it hears more than one broadcast. Probe can also send the limited broadcast once per interface, from a socket bound to that interface, and over IPv6.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Destinations added in v0.2.0

func Destinations(dst *net.UDPAddr, o *Options) ([]*net.UDPAddr, error)

Destinations returns the addresses Send would send to for dst and o, in sending order.

Example

Destinations shows where Send would send. An IPv6 link-local multicast address without a zone becomes one address per interface; with a zone it is used as given.

package main

import (
	"fmt"
	"net"

	"github.com/cB-Sigma/lanbcast"
)

func main() {
	zoned := &net.UDPAddr{IP: net.IPv6linklocalallnodes, Port: 5683, Zone: "en0"}
	d, err := lanbcast.Destinations(zoned, nil)
	fmt.Println(d, err)

	// Without a zone: one address per interface, the zone holding the
	// interface name (for example "en0" or "eth0"). How many depends on
	// the host.
	_, err = lanbcast.Destinations(&net.UDPAddr{IP: net.IPv6linklocalallnodes, Port: 5683}, nil)
	fmt.Println(err)
}
Output:
[[ff02::1%en0]:5683] <nil>
<nil>

func Probe added in v0.2.0

func Probe(ctx context.Context, payload []byte, port int, o *ProbeOptions, handle func(Answer)) error

Probe sends payload to UDP port port on the LAN and passes each answer to handle until ctx ends; it then returns nil. By default it sends over IPv4 to 255.255.255.255 and to every chosen interface's directed broadcast address from one socket; o can add IPv6 and per-interface sockets. handle is called from Probe's goroutine, one answer at a time. A ctx without a deadline must be cancelled to stop Probe.

Probe fails when no socket could be opened, when no send succeeded, or when a socket read fails for a reason other than ctx ending.

Example

Probe opens its own sockets: here one per LAN interface, each bound to that interface so the limited broadcast leaves through every LAN, plus an IPv6 socket for ff02::1. It needs a network, so it has no output.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/cB-Sigma/lanbcast"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	opts := &lanbcast.ProbeOptions{PerInterface: true, IPv6: true, Resends: 1}
	err := lanbcast.Probe(ctx, []byte(`{"method":"getPilot","params":{}}`), 38899, opts, func(a lanbcast.Answer) {
		fmt.Println(a.From, a.Interface, string(a.Data))
	})
	if err != nil {
		fmt.Println(err)
	}
}

func ProbeConn added in v0.2.0

func ProbeConn(ctx context.Context, c net.PacketConn, payload []byte, dst *net.UDPAddr, o *ProbeOptions, handle func(Answer)) error

ProbeConn is Probe over the caller's socket c: it sends payload to dst with Send and passes each answer read from c to handle until ctx ends. The IPv6, PerInterface and LocalPort fields of o are not used; for IPv6, pass an IPv6 socket and an ff02::/16 destination. ProbeConn sets c's read deadline while it runs and clears it on return; it does not close c.

Example

ProbeConn sends a probe on the caller's socket and passes each answer to a callback until the context ends. Here a device on the loopback interface answers twice with the same bytes; the copy is dropped.

package main

import (
	"context"
	"fmt"
	"net"
	"time"

	"github.com/cB-Sigma/lanbcast"
)

func main() {
	device, _ := net.ListenPacket("udp4", "127.0.0.1:0")
	defer device.Close()
	go func() {
		buf := make([]byte, 64)
		_, from, err := device.ReadFrom(buf)
		if err == nil {
			device.WriteTo([]byte(`{"mac":"a8bb50000001"}`), from)
			device.WriteTo([]byte(`{"mac":"a8bb50000001"}`), from)
		}
	}()

	conn, _ := net.ListenPacket("udp4", "127.0.0.1:0")
	defer conn.Close()
	ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
	defer cancel()
	err := lanbcast.ProbeConn(ctx, conn, []byte(`{"method":"getPilot"}`), device.LocalAddr().(*net.UDPAddr), nil,
		func(a lanbcast.Answer) { fmt.Println(string(a.Data)) })
	fmt.Println(err)
}
Output:
{"mac":"a8bb50000001"}
<nil>

func Send added in v0.2.0

func Send(c net.PacketConn, payload []byte, dst *net.UDPAddr, o *Options) error

Send sends payload to dst like WriteBroadcast, choosing interfaces by o (nil means the zero Options). dst is expanded as follows:

  • 255.255.255.255: sent there, then to the directed broadcast address of every chosen interface that can broadcast.
  • an IPv6 link-local multicast address (ff02::/16, for example net.IPv6linklocalallnodes) without a zone: sent once per chosen interface that is multicast-capable and has an IPv6 link-local address, with the interface name as zone. The connection must be an IPv6 socket, such as net.ListenPacket("udp6", "[::]:0").
  • anything else: sent to dst alone.

It fails only when no send succeeded, with the first error, or when an interface pattern in o is malformed.

Example

Send with Options limits the interfaces by name. Here no interface matches, so only the limited broadcast itself goes out. Tunnel and VPN interfaces are skipped unless named or AllowTunnels is set.

package main

import (
	"fmt"
	"net"

	"github.com/cB-Sigma/lanbcast"
)

// recorder is a net.PacketConn that records where datagrams were sent.
type recorder struct {
	net.PacketConn
	sent []string
}

func (r *recorder) WriteTo(b []byte, a net.Addr) (int, error) {
	r.sent = append(r.sent, a.String())
	return len(b), nil
}

func main() {
	conn := &recorder{}
	probe := []byte(`{"method":"getPilot","params":{}}`)
	opts := &lanbcast.Options{Interfaces: []string{"no-such-interface"}}

	err := lanbcast.Send(conn, probe, &net.UDPAddr{IP: net.IPv4bcast, Port: 38899}, opts)
	fmt.Println(conn.sent, err)
}
Output:
[255.255.255.255:38899] <nil>

func TunnelNames added in v0.2.0

func TunnelNames() []string

TunnelNames returns the interface name patterns that Send, Probe and ProbeConn skip unless Options.AllowTunnels is set or the interface is named in Options.Interfaces. The slice is a copy.

func WriteBroadcast

func WriteBroadcast(c net.PacketConn, payload []byte, dst *net.UDPAddr) error

WriteBroadcast sends one discovery datagram to dst. When dst is the limited broadcast address it also goes to the directed broadcast address (for example 192.168.0.255) of every LAN interface that is up: a host with a VPN or several interfaces may route 255.255.255.255 somewhere it cannot be sent (macOS answers "can't assign requested address" while a VPN tunnel holds that route), and the directed address still reaches the LAN. A device that hears both answers twice; callers already key answers by device. It fails only when no send succeeded, with the first error.

WriteBroadcast skips only loopback, point-to-point and non-broadcast interfaces, as it did in v0.1. Send also skips interfaces named like VPN and tunnel interfaces and takes Options.

Example

Send a discovery probe to the limited broadcast address. It goes there first, then to the directed broadcast address of each LAN interface of this host (how many depends on the host). Any other destination is sent to alone. In real use the connection is a UDP socket from net.ListenPacket("udp4", ":0").

package main

import (
	"fmt"
	"net"

	"github.com/cB-Sigma/lanbcast"
)

// recorder is a net.PacketConn that records where datagrams were sent.
type recorder struct {
	net.PacketConn
	sent []string
}

func (r *recorder) WriteTo(b []byte, a net.Addr) (int, error) {
	r.sent = append(r.sent, a.String())
	return len(b), nil
}

func main() {
	conn := &recorder{}
	probe := []byte(`{"method":"getPilot","params":{}}`)

	err := lanbcast.WriteBroadcast(conn, probe, &net.UDPAddr{IP: net.IPv4bcast, Port: 38899})
	fmt.Println("first send:", conn.sent[0], err)

	conn.sent = nil
	err = lanbcast.WriteBroadcast(conn, probe, &net.UDPAddr{IP: net.IPv4(192, 168, 7, 255), Port: 38899})
	fmt.Println("explicit address:", conn.sent, err)
}
Output:
first send: 255.255.255.255:38899 <nil>
explicit address: [192.168.7.255:38899] <nil>

Types

type Answer added in v0.2.0

type Answer struct {
	// From is the sender. An IPv6 link-local sender carries its zone.
	From *net.UDPAddr
	// Data is the datagram.
	Data []byte
	// Interface names the interface the answer came in on. On Linux,
	// macOS and Windows the kernel reports it for each datagram (packet
	// information control messages). Otherwise it is the interface the
	// socket was bound to (ProbeOptions.PerInterface), else the zone of
	// an IPv6 link-local sender, else the interface whose IPv4 subnet
	// holds the sender's address (an inference: overlapping subnets pick
	// the first). It is empty when none applies, for example for a sender
	// outside every local subnet on a system without packet information.
	Interface string
	// InterfaceExact reports that Interface was not inferred from a
	// subnet: it came from the kernel, the socket's binding or the zone.
	InterfaceExact bool
}

Answer is one datagram received after a probe.

func Collect added in v0.2.0

func Collect(ctx context.Context, payload []byte, port int, o *ProbeOptions) ([]Answer, error)

Collect runs Probe and returns the answers in the order they arrived.

Example

Collect returns the answers of a probe as a slice.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/cB-Sigma/lanbcast"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	answers, err := lanbcast.Collect(ctx, []byte{0x21, 0x31, 0x00, 0x20}, 54321, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, a := range answers {
		fmt.Println(a.From.IP)
	}
}

type Options added in v0.2.0

type Options struct {
	// Interfaces, when not empty, limits sends to interfaces whose name
	// matches one of these patterns (path.Match syntax, compared without
	// regard to case). An interface named here is used even when its name
	// is also on the tunnel list; point-to-point links still need
	// AllowTunnels.
	Interfaces []string

	// Exclude skips interfaces whose name matches one of these patterns
	// (path.Match syntax, compared without regard to case). It wins over
	// Interfaces.
	Exclude []string

	// AllowTunnels turns off the default exclusion of point-to-point
	// interfaces and of the names in [TunnelNames].
	AllowTunnels bool

	// Filter, when set, is asked about every interface that passed the
	// other rules; returning false skips it.
	Filter func(net.Interface) bool
}

Options chooses the interfaces Send, Destinations, Probe and ProbeConn use. The zero value uses every interface that is up and not a loopback, point-to-point or tunnel interface (see TunnelNames).

type ProbeOptions added in v0.2.0

type ProbeOptions struct {
	// Options chooses the interfaces.
	Options

	// KeepDuplicates passes every datagram to the callback. By default a
	// datagram with the same sender and the same bytes as an earlier one
	// is dropped: a device that hears both the limited and a directed
	// broadcast usually answers twice.
	KeepDuplicates bool

	// Resends is how many more times the probe is sent while waiting for
	// answers, ResendInterval apart (default one second). Broadcasts are
	// lost more easily than unicasts.
	Resends        int
	ResendInterval time.Duration

	// BufferSize is the largest answer read, in bytes (default 65535).
	BufferSize int

	// LocalPort is the local UDP port to send from and receive on
	// (default: one chosen by the system). Some devices answer to a fixed
	// port rather than to the sender's.
	LocalPort int

	// IPv6 also sends the probe from an IPv6 socket to the all-nodes
	// link-local multicast group ff02::1 on every chosen interface. Many
	// devices that answer vendor broadcast probes speak IPv4 only.
	IPv6 bool

	// PerInterface sends the limited broadcast from one socket per chosen
	// interface, bound to that interface's IPv4 address, instead of once
	// through the routing table. It reaches devices that only hear
	// 255.255.255.255, such as devices without an address in the LAN's
	// subnet, on every interface instead of only the one the routing table
	// picks. The directed broadcast of each interface goes from the same
	// socket. See the README for how each operating system honours it.
	PerInterface bool
}

ProbeOptions configures Probe, ProbeConn and Collect. The zero value sends once, over IPv4, through one socket, and drops duplicates.

type Request added in v0.3.0

type Request struct {
	// From is the sender; a reply goes there.
	From *net.UDPAddr
	// Data is the datagram.
	Data []byte
	// Interface names the interface the datagram came in on, as
	// [Answer.Interface] does, with InterfaceExact saying whether it was
	// reported by the kernel (Linux, macOS, Windows) or inferred.
	Interface      string
	InterfaceExact bool
}

Request is a datagram a Responder received.

type RespondOptions added in v0.3.0

type RespondOptions struct {
	// Options, when any of its fields is set, chooses the interfaces
	// requests are taken from (as for sending: tunnels are skipped unless
	// AllowTunnels); a request that arrives on another interface is
	// dropped. The zero value takes requests from every interface but
	// loopback.
	Options

	// Loopback also takes requests that arrive on a loopback interface
	// (a probe sent on the same host, as tests do).
	Loopback bool

	// IPv6 also listens on an IPv6 socket on the same port, for probes
	// sent to ff02::1 or another link-local group. The socket joins no
	// group: ff02::1 reaches every node without joining.
	IPv6 bool

	// Address is the IPv4 address to listen on (default: all). Binding to
	// a unicast address stops broadcasts from arriving on most systems.
	Address net.IP

	// BufferSize is the largest request read, in bytes (default 65535).
	BufferSize int
}

RespondOptions configures a Responder. The zero value listens over IPv4 on every interface.

type Responder added in v0.3.0

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

Responder answers discovery probes: the device side of Probe. It is what a simulator, an emulated device or a test peer needs: listen on a UDP port on every LAN interface, see which interface each probe came in on, and answer to the sender from the same socket.

Example

A device's side: answer probes on a UDP port, here probed over loopback.

package main

import (
	"context"
	"fmt"
	"net"
	"time"

	"github.com/cB-Sigma/lanbcast"
)

func main() {
	r, err := lanbcast.NewResponder(0, &lanbcast.RespondOptions{Loopback: true})
	if err != nil {
		fmt.Println(err)
		return
	}
	defer r.Close()
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	go r.Serve(ctx, func(q lanbcast.Request) []byte {
		if string(q.Data) == "who is there?" {
			return []byte(`{"model":"demo-bulb"}`)
		}
		return nil
	})

	c, err := net.ListenPacket("udp4", "127.0.0.1:0")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer c.Close()
	pctx, pcancel := context.WithTimeout(ctx, 300*time.Millisecond)
	defer pcancel()
	to := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: r.LocalAddr().Port}
	_ = lanbcast.ProbeConn(pctx, c, []byte("who is there?"), to, nil, func(a lanbcast.Answer) {
		fmt.Println(string(a.Data))
	})
}
Output:
{"model":"demo-bulb"}

func NewResponder added in v0.3.0

func NewResponder(port int, o *RespondOptions) (*Responder, error)

NewResponder opens the sockets on UDP port port. Close releases them.

func (*Responder) Close added in v0.3.0

func (r *Responder) Close() error

Close closes the sockets; Serve then returns.

func (*Responder) LocalAddr added in v0.3.0

func (r *Responder) LocalAddr() *net.UDPAddr

LocalAddr is the IPv4 socket's address (with the port chosen by the system when port was 0).

func (*Responder) Serve added in v0.3.0

func (r *Responder) Serve(ctx context.Context, handle func(Request) []byte) error

Serve reads requests until ctx ends or the Responder is closed, and calls handle for each, one at a time; a non-empty reply is sent to the sender from the socket the request came in on. Serve returns nil when ctx ends or Close was called, and the first read error otherwise.

Jump to

Keyboard shortcuts

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