在golang中本地发送UDPv6

Sending UDPv6 locally in golang

我需要发送一个 UDPv6 数据报,以便本地接收方(或通过 tcpdump)跟踪此消息。

daddr, err = net.ResolveUDPAddr("udp6", "[address]:port")
if err != nil {
    return err
}

conn, err := net.DialUDP("udp6", nil, daddr)
if err != nil {
    return err
}
defer conn.Close()

conn.Write(...)

与 IPv4 不同,此代码不适用于 IPv6。例如,当我尝试将数据报发送到多播地址时,例如到 [FF01::DB8:0:0]:5000,我得到 connect: invalid argument。当我尝试将它发送到 [fe80::20c:29ff:fee1:d66]:5000(我的 IPv6 地址根据 ifconfig)时,也会发生同样的情况。

在这两种情况下(link-local 和 interface-local 多播)您都忘记了指定作用域 ID。没有这个,就不可能确定使用哪个接口,并且你会从操作系统中得到一个 Invalid argument 错误。

net.UDPAddr uses the Zone field to store the scope ID. You need to ensure that you have provided one, either by setting Zone explicitly or by using the percent-suffix notation.