Skip to content

Instantly share code, notes, and snippets.

@raszia
Last active March 9, 2023 07:33
Show Gist options
  • Save raszia/19f3b86033e02edbd043e5d07dc3b70e to your computer and use it in GitHub Desktop.
Save raszia/19f3b86033e02edbd043e5d07dc3b70e to your computer and use it in GitHub Desktop.
multicast with golang
package main
import (
"fmt"
"net"
"golang.org/x/net/ipv4"
)
func main() {
// resolve the multicast address and port
addr, err := net.ResolveUDPAddr("udp", "224.0.0.1:8888")
if err != nil {
panic(err)
}
// resolve the local address and port
laddr, err := net.ResolveUDPAddr("udp", "0.0.0.0:0")
if err != nil {
panic(err)
}
// create the local UDP connection
conn, err := net.ListenUDP("udp", laddr)
if err != nil {
panic(err)
}
// join the multicast group
ifi, err := net.InterfaceByName("enxa8637d613a92") // replace with your network interface name
if err != nil {
panic(err)
}
p := ipv4.NewPacketConn(conn)
if err := p.JoinGroup(ifi, addr); err != nil {
panic(err)
}
// start a goroutine to receive messages
go func() {
for {
buf := make([]byte, 1024)
n, _, _, err := p.ReadFrom(buf)
if err != nil {
panic(err)
}
fmt.Printf("Received message: %s\n", string(buf[:n]))
}
}()
// send some messages to the multicast group
for i := 0; i < 10; i++ {
message := fmt.Sprintf("Hello, multicast group! (%d)", i)
if _, err := p.WriteTo([]byte(message), nil, addr); err != nil {
panic(err)
}
fmt.Printf("Sent message: %s\n", message)
}
}
@raszia
Copy link
Author

raszia commented Feb 19, 2023

use ListenUDP to create a local UDP connection and then join the multicast group using the JoinGroup method of an ipv4.PacketConn structure, which is created from the net.UDPConn. We also use the WriteTo method of the ipv4.PacketConn to send messages to the group. Finally, we use the ReadFrom method of the ipv4.PacketConn to receive messages from the group in a goroutine.

Note that you'll need to replace "enxa8637d613a92" with the name of the network interface you want to use for multicasting, and ensure that your network supports multicast.

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