From 029f90de6895b68b5f3d1999858b09d055429679 Mon Sep 17 00:00:00 2001 From: Ethel Morgan Date: Fri, 19 Jun 2020 23:50:49 +0100 Subject: basic wake-on-lan actuator --- wakeonlan/wakeonlan.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 wakeonlan/wakeonlan.go (limited to 'wakeonlan/wakeonlan.go') diff --git a/wakeonlan/wakeonlan.go b/wakeonlan/wakeonlan.go new file mode 100644 index 0000000..803d27f --- /dev/null +++ b/wakeonlan/wakeonlan.go @@ -0,0 +1,43 @@ +// Package wakeonlan implements Wake-On-Lan. +package wakeonlan + +import ( + "bytes" + "encoding/binary" + "fmt" + "net" +) + +var ( + header = []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} + + broadcastAddr = &net.UDPAddr{ + IP: net.IPv4bcast, + Port: 9, + } +) + +// Wake sends the Magic Packet to wake the computer with the given MAC address. +func Wake(mac net.HardwareAddr) error { + conn, err := net.DialUDP("udp", nil, broadcastAddr) + if err != nil { + return fmt.Errorf("could not create UDP broadcast: %w", err) + } + defer conn.Close() + + payload := packet(mac) + + if _, err := conn.Write(payload); err != nil { + return fmt.Errorf("could not send Magic Packet: %w", err) + } + return nil +} + +func packet(mac net.HardwareAddr) []byte { + var buf bytes.Buffer + binary.Write(&buf, binary.BigEndian, header) + for i := 0; i < 16; i++ { + binary.Write(&buf, binary.BigEndian, mac) + } + return buf.Bytes() +} -- cgit v1.2.3