github.com/laof/lite-speed-test@v0.0.0-20230930011949-1f39b7037845/transport/dialer/system_listener.go (about) 1 package dialer 2 3 import ( 4 "context" 5 "net" 6 "syscall" 7 8 "github.com/laof/lite-speed-test/common" 9 "github.com/laof/lite-speed-test/log" 10 ) 11 12 var ( 13 effectiveListener = DefaultListener{} 14 ) 15 16 type DefaultListener struct { 17 controllers []controller 18 } 19 20 func getControlFunc(ctx context.Context, controllers []controller) func(network, address string, c syscall.RawConn) error { 21 return func(network, address string, c syscall.RawConn) error { 22 return c.Control(func(fd uintptr) { 23 24 setReusePort(fd) // nolint: staticcheck 25 26 for _, controller := range controllers { 27 if err := controller(network, address, fd); err != nil { 28 log.E("failed to apply external controller") 29 continue 30 } 31 } 32 }) 33 } 34 } 35 36 // func setReusePort(fd uintptr) error { 37 // if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil { 38 // return common.NewError("failed to set SO_REUSEPORT") 39 // } 40 // return nil 41 // } 42 43 func (dl *DefaultListener) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) { 44 var lc net.ListenConfig 45 46 lc.Control = getControlFunc(ctx, dl.controllers) 47 48 return lc.ListenPacket(ctx, network, address) 49 } 50 51 func RegisterListenerController(controller func(network, address string, fd uintptr) error) error { 52 if controller == nil { 53 return common.NewError("nil listener controller") 54 } 55 56 effectiveListener.controllers = append(effectiveListener.controllers, controller) 57 return nil 58 }