-
Notifications
You must be signed in to change notification settings - Fork 69
/
multicast.go
39 lines (29 loc) · 917 Bytes
/
multicast.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
package main
import (
"fmt"
"net"
"runtime"
"golang.org/x/net/ipv6"
)
const osWindows = "windows"
// ListenUDPMulticast listens on a multicast group in a way that is supported on
// Unix and Windows for both IPv4 and IPv6.
func ListenUDPMulticast(iface *net.Interface, multicastGroup *net.UDPAddr) (net.PacketConn, error) {
if multicastGroup.IP.To4() != nil {
return net.ListenMulticastUDP("udp", iface, multicastGroup)
}
if runtime.GOOS != osWindows {
return net.ListenMulticastUDP("udp6", iface, multicastGroup)
}
listenAddr := &net.UDPAddr{IP: multicastGroup.IP, Port: multicastGroup.Port}
conn, err := net.ListenPacket("udp6", listenAddr.String())
if err != nil {
return nil, err
}
packetConn := ipv6.NewPacketConn(conn)
err = packetConn.JoinGroup(iface, listenAddr)
if err != nil {
return nil, fmt.Errorf("join multicast group %s: %w", listenAddr.IP, err)
}
return conn, nil
}