From 282c5f94f07c803d947ff07eb9dd150123fb0ede Mon Sep 17 00:00:00 2001 From: Gray Liang Date: Fri, 5 Jan 2024 20:08:10 +0800 Subject: [PATCH] Use netns only if EADDRINUSE occurred --- control/anyfrom_pool.go | 6 +----- control/udp.go | 17 ++++++++--------- 2 files changed, 9 insertions(+), 14 deletions(-) diff --git a/control/anyfrom_pool.go b/control/anyfrom_pool.go index b10354ff54..f7206178db 100644 --- a/control/anyfrom_pool.go +++ b/control/anyfrom_pool.go @@ -190,11 +190,7 @@ func (p *AnyfromPool) GetOrCreate(lAddr string, ttl time.Duration) (conn *Anyfro }, KeepAlive: 0, } - var pc net.PacketConn - err := WithIndieNetns(func() (err error) { - pc, err = d.ListenPacket(context.Background(), "udp", lAddr) - return err - }) + pc, err := d.ListenPacket(context.Background(), "udp", lAddr) if err != nil { return nil, true, err } diff --git a/control/udp.go b/control/udp.go index e0ed524c2a..d3c380ef09 100644 --- a/control/udp.go +++ b/control/udp.go @@ -90,17 +90,16 @@ func sendPkt(data []byte, from netip.AddrPort, realTo, to netip.AddrPort, lConn } uConn, _, err := DefaultAnyfromPool.GetOrCreate(from.String(), AnyfromTimeout) - if err != nil { - if errors.Is(err, syscall.EADDRINUSE) { - // Port collision, use traditional method. - return sendPktWithHdrWithFlag(data, from, lConn, to, lanWanFlag) - } - return err + if err != nil && errors.Is(err, syscall.EADDRINUSE) { + err = WithIndieNetns(func() (err error) { + uConn, _, err = DefaultAnyfromPool.GetOrCreate(from.String(), AnyfromTimeout) + return err + }) } - err = WithIndieNetns(func() (err error) { - _, err = uConn.WriteToUDPAddrPort(data, realTo) + if err != nil { return - }) + } + _, err = uConn.WriteToUDPAddrPort(data, realTo) return err }