vppn/node/localbroadcaster.go
2024-12-30 09:26:48 +01:00

76 lines
1.5 KiB
Go

package node
import (
"encoding/binary"
"log"
"net"
"net/netip"
"time"
)
func localBroadcaster() {
var (
buf1 = make([]byte, bufferSize)
buf2 = make([]byte, bufferSize)
)
time.Sleep(4 * time.Second)
doBroadcast(buf1, buf2)
for range time.Tick(32 * time.Second) {
doBroadcast(buf1, buf2)
}
}
func doBroadcast(buf1, buf2 []byte) {
ifaces, err := net.Interfaces()
if err != nil {
log.Printf("Failed to list interfaces: %v", err)
return
}
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagRunning == 0 {
continue
}
if iface.Flags&net.FlagPointToPoint != 0 {
continue
}
if iface.Flags&net.FlagBroadcast == 0 {
continue
}
addrs, err := iface.Addrs()
if err != nil {
log.Printf("Failed to get interface addresses: %v", err)
continue
}
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if !ok {
continue
}
ip4 := ipNet.IP.To4()
if ip4 == nil {
continue
}
ip, ok := lastAddr(ipNet)
if !ok {
log.Printf("Failed to find broadcast address: %v", ipNet)
continue
}
log.Printf("Broadcasting on address: %v", ip)
//addr := netip.AddrPortFrom(ip, 456)
}
}
}
// works when the n is a prefix, otherwise...
func lastAddr(n *net.IPNet) (netip.Addr, bool) {
ip := make(net.IP, len(n.IP.To4()))
binary.BigEndian.PutUint32(ip, binary.BigEndian.Uint32(n.IP.To4())|
^binary.BigEndian.Uint32(net.IP(n.Mask).To4()))
return netip.AddrFromSlice(ip)
}