44 lines
1.0 KiB
Go
44 lines
1.0 KiB
Go
package peer
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"fmt"
|
|
"log"
|
|
"net"
|
|
"time"
|
|
)
|
|
|
|
const beaconLen = 35 // 1 VPN IP byte + 32 WG pubkey + 2 WG listen port
|
|
|
|
func RunMCWriter(g Globals) {
|
|
conn, err := net.ListenMulticastUDP("udp", nil, multicastAddr)
|
|
if err != nil {
|
|
log.Fatalf("[MCWriter] bind: %v", err)
|
|
}
|
|
|
|
for range time.Tick(broadcastInterval) {
|
|
beacon, err := buildBeacon(g)
|
|
if err != nil {
|
|
log.Printf("[MCWriter] build beacon: %v", err)
|
|
continue
|
|
}
|
|
log.Printf("[MCWriter] Broadcasting on %v...", multicastAddr)
|
|
if _, err := conn.WriteToUDP(beacon, multicastAddr); err != nil {
|
|
log.Printf("[MCWriter] write: %v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func buildBeacon(g Globals) ([]byte, error) {
|
|
dev, err := g.WGClient.Device(g.WGDevName)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("get WG device: %w", err)
|
|
}
|
|
beacon := make([]byte, beaconLen)
|
|
beacon[0] = g.LocalPeerIP
|
|
pubKey := g.WGPrivKey.PublicKey()
|
|
copy(beacon[1:33], pubKey[:])
|
|
binary.BigEndian.PutUint16(beacon[33:35], uint16(dev.ListenPort))
|
|
return beacon, nil
|
|
}
|