Golang接受ipv6组播包的例子

July 05, 2024 | 1 Minute Read

参考https://pkg.go.dev/golang.org/x/net/ipv6 , 可以用 “ip maddress show dev enp0s8 “ 和 “cat /proc/net/igmp6 ” “ss -lnp” 等命令查看组播监听状态

package main

import (
        // "os"
        "net"
        "fmt"
        "time"
        "golang.org/x/net/ipv6"
)

func main() {
        en0, err := net.InterfaceByName("enp0s8")
        if err != nil {
                fmt.Println("err ifname")
                return;
        }
        c, err := net.ListenPacket("ip6:58", "::")
        if err != nil {
                fmt.Println("err listen")
                return;
        }
        defer c.Close()
        p := ipv6.NewPacketConn(c)
        mcRouters := net.IPAddr{IP: net.ParseIP("ff02::16")}
        if err := p.JoinGroup(en0, &mcRouters); err != nil {
                fmt.Println("err join")
                return;
        }
        fmt.Println("okk")
        time.Sleep(time.Second * 3600)
}