miniwol/lib/packet.go
2022-02-17 13:31:01 +01:00

51 lines
819 B
Go

package lib
import (
"net"
)
// Sends a magic packet
func SendPacket(from, to, macStr string) error {
// Get a binary representation of that MAC Address
mac, err := net.ParseMAC(macStr)
if err != nil {
return err
}
// Construct the Magic Packet
packet := make([]byte, 102)
index := 0
for i := 0; i < 6; i++ {
packet[index] = 0xFF
index++
}
for i := 0; i < 16; i++ {
for j := 0; j < 6; j++ {
packet[index] = mac[j]
index++
}
}
// Resolve addresses
localAddr, err := net.ResolveUDPAddr("udp4", from)
if err != nil {
return err
}
broadcastAddr, err := net.ResolveUDPAddr("udp4", to)
if err != nil {
return err
}
// Send packet
conn, err := net.DialUDP("udp4", localAddr, broadcastAddr)
if err != nil {
return err
}
defer conn.Close()
conn.Write(packet)
return nil
}