Created
March 20, 2014 13:55
-
-
Save fiorix/9664255 to your computer and use it in GitHub Desktop.
Go multicast example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
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.
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
@freignat91 Is multicast enabled on your router?