Skip to content

Instantly share code, notes, and snippets.

@fiorix
Created March 20, 2014 13:55
Show Gist options
  • Save fiorix/9664255 to your computer and use it in GitHub Desktop.
Save fiorix/9664255 to your computer and use it in GitHub Desktop.
Go multicast example
package main
import (
"encoding/hex"
"log"
"net"
"time"
)
const (
srvAddr = "224.0.0.1:9999"
maxDatagramSize = 8192
)
func main() {
go ping(srvAddr)
serveMulticastUDP(srvAddr, msgHandler)
}
func ping(a string) {
addr, err := net.ResolveUDPAddr("udp", a)
if err != nil {
log.Fatal(err)
}
c, err := net.DialUDP("udp", nil, addr)
for {
c.Write([]byte("hello, world\n"))
time.Sleep(1 * time.Second)
}
}
func msgHandler(src *net.UDPAddr, n int, b []byte) {
log.Println(n, "bytes read from", src)
log.Println(hex.Dump(b[:n]))
}
func serveMulticastUDP(a string, h func(*net.UDPAddr, int, []byte)) {
addr, err := net.ResolveUDPAddr("udp", a)
if err != nil {
log.Fatal(err)
}
l, err := net.ListenMulticastUDP("udp", nil, addr)
l.SetReadBuffer(maxDatagramSize)
for {
b := make([]byte, maxDatagramSize)
n, src, err := l.ReadFromUDP(b)
if err != nil {
log.Fatal("ReadFromUDP failed:", err)
}
h(src, n, b)
}
}
@0xcaff
Copy link

0xcaff commented Apr 25, 2017

@freignat91 Is multicast enabled on your router?

@morrowc
Copy link

morrowc commented Jun 13, 2017

Note that the switch may need mcast enabled (igmp snooping) and then the router (if it goes from switch to router to switch) will also have to understand what to do about mcast packets.

@fabiensanglard
Copy link

Unsurprisingly, it does not work on MacOS X but that is because they don't load balance on SO_REUSEPORT.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment