From 4b1e72c7813a563f19df5e4842cc6585751b934f Mon Sep 17 00:00:00 2001 From: Xu Liu Date: Wed, 25 Sep 2024 17:07:32 +0800 Subject: [PATCH] Bind to correct interface by specifying zone index Signed-off-by: Xu Liu --- conn.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/conn.go b/conn.go index b4c0707..f0d591b 100644 --- a/conn.go +++ b/conn.go @@ -6,6 +6,7 @@ import ( "net" "net/netip" "runtime" + "strconv" "time" "golang.org/x/net/icmp" @@ -45,8 +46,10 @@ func Listen(ifi *net.Interface, addr Addr) (*Conn, netip.Addr, error) { if err != nil { return nil, netip.Addr{}, err } - - ic, err := icmp.ListenPacket("ip6:ipv6-icmp", ip.String()) + // Specify the zone index to bind to the correct interface. + // The zone index is cached in https://github.com/golang/go/blob/go1.23.1/src/net/interface.go#L192 + // and may result in binding on the wrong interface if using the interface name as zone. + ic, err := icmp.ListenPacket("ip6:ipv6-icmp", ip.WithZone(strconv.Itoa(ifi.Index)).String()) if err != nil { return nil, netip.Addr{}, err }