Golang 中在多播 UDP 连接上启用 IP_MULTICAST_LOOP
要在多播 UDP 连接上启用 IP_MULTICAST_LOOP,net.ListenMulticastUDP 函数可用,但其局限性包括:
使用 golang.org/x/ 的解决方案net/ipv4
为了获得更大的灵活性,请考虑using golang.org/x/net/ipv4:
示例代码:
package main import ( "fmt" "net" "golang.org/x/net/ipv4" ) func main() { // IPv4 address for multicast ipv4Addr := &net.UDPAddr{IP: net.IPv4(224, 0, 0, 251), Port: 5352} // Dial a UDP connection conn, err := net.ListenUDP("udp4", ipv4Addr) if err != nil { fmt.Printf("Error dialing: %v\n", err) return } // Create a packet connection from the UDP connection pc := ipv4.NewPacketConn(conn) // Assume an interface named "wlan" iface, err := net.InterfaceByName("wlan") if err != nil { fmt.Printf("Could not find interface %v\n", err) return } // Join the multicast group on the specified interface if err = pc.JoinGroup(iface, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 251)}); err != nil { fmt.Printf("Failed to join multicast group: %v\n", err) return } // Get and set multicast loopback status loop, err := pc.MulticastLoopback() if err != nil { fmt.Printf("Failed to get multicast loopback status: %v\n", err) } fmt.Printf("Multicast loopback status: %v\n", loop) if !loop { if err = pc.SetMulticastLoopback(true); err != nil { fmt.Printf("Could not set multicast loopback: %v\n", err) return } } // Send a message on the multicast address if _, err = conn.WriteTo([]byte("hello"), ipv4Addr); err != nil { fmt.Printf("Error sending multicast message: %v\n", err) } // Reading multicast messages buf := make([]byte, 1024) for { n, addr, err := conn.ReadFrom(buf) if err != nil { fmt.Printf("Error in multicast message reception: %v\n", err) } fmt.Printf("Message received: %s from %v\n", buf[:n], addr) } }
按照以下步骤,您可以有效设置 IP_MULTICAST_LOOP 和在本地计算机上发送/接收多播数据包。
以上是如何在 Golang 中的多播 UDP 连接上设置 IP_MULTICAST_LOOP?的详细内容。更多信息请关注PHP中文网其他相关文章!