-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
51 lines (44 loc) · 1.05 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"encoding/hex"
"fmt"
"log"
"net"
"flag"
)
var maddr = flag.String("a", "", "Multicast address to broadcast to")
var intf = flag.String("i", "", "Multicast interface to listen on")
const (
maxDatagramSize = 8192
)
func main() {
flag.Parse()
serveMulticastUDP(*maddr, msgHandler)
}
func msgHandler(src *net.UDPAddr, n int, b []byte) {
log.Println(n, "bytes read from", src)
log.Println("\n" + hex.Dump(b[:n]))
}
func serveMulticastUDP(a string, h func(*net.UDPAddr, int, []byte)) {
fmt.Println("Listening to:", a)
addr, err := net.ResolveUDPAddr("udp", a)
if err != nil {
log.Fatal(err)
}
iface, err := net.InterfaceByName( *intf )
if err != nil {
log.Println("Error using interface:", *intf, "Error:", err)
iface = nil
}
l, err := net.ListenMulticastUDP("udp", iface, addr)
l.SetReadBuffer(maxDatagramSize)
b := make([]byte, maxDatagramSize)
for {
bytesRead, src, err := l.ReadFromUDP(b)
if (err != nil) {
log.Fatal("ReadFromUDP failed:", err)
}
if (bytesRead == 0) { continue; }
h(src, bytesRead, b)
}
}