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 ¶
- func Destinations(dst *net.UDPAddr, o *Options) ([]*net.UDPAddr, error)
- func Probe(ctx context.Context, payload []byte, port int, o *ProbeOptions, ...) error
- func ProbeConn(ctx context.Context, c net.PacketConn, payload []byte, dst *net.UDPAddr, ...) error
- func Send(c net.PacketConn, payload []byte, dst *net.UDPAddr, o *Options) error
- func TunnelNames() []string
- func WriteBroadcast(c net.PacketConn, payload []byte, dst *net.UDPAddr) error
- type Answer
- type Options
- type ProbeOptions
- type Request
- type RespondOptions
- type Responder
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Destinations ¶ added in v0.2.0
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)
}
}
Output:
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
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 ¶
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
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)
}
}
Output:
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) LocalAddr ¶ added in v0.3.0
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
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.