trpc.group/trpc-go/trpc-go@v1.0.3/internal/reuseport/reuseport.go (about) 1 // 2 // 3 // Tencent is pleased to support the open source community by making tRPC available. 4 // 5 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 6 // All rights reserved. 7 // 8 // If you have downloaded a copy of the tRPC source code from Tencent, 9 // please note that tRPC source code is licensed under the Apache 2.0 License, 10 // A copy of the Apache 2.0 License is included in this file. 11 // 12 // 13 14 //go:build linux || darwin || dragonfly || freebsd || netbsd || openbsd 15 // +build linux darwin dragonfly freebsd netbsd openbsd 16 17 // Package reuseport provides a function that returns a net.Listener powered 18 // by a net.FileListener with a SO_REUSEPORT option set to the socket. 19 package reuseport 20 21 import ( 22 "errors" 23 "fmt" 24 "net" 25 "os" 26 "syscall" 27 ) 28 29 const fileNameTemplate = "reuseport.%d.%s.%s" 30 31 var errUnsupportedProtocol = errors.New("only tcp, tcp4, tcp6, udp, udp4, udp6 are supported") 32 33 // getSockaddr parses protocol and address and returns implementor 34 // of syscall.Sockaddr: syscall.SockaddrInet4 or syscall.SockaddrInet6. 35 func getSockaddr(proto, addr string) (sa syscall.Sockaddr, soType int, err error) { 36 switch proto { 37 case "tcp", "tcp4", "tcp6": 38 return getTCPSockaddr(proto, addr) 39 case "udp", "udp4", "udp6": 40 return getUDPSockaddr(proto, addr) 41 default: 42 return nil, -1, errUnsupportedProtocol 43 } 44 } 45 46 func getSocketFileName(proto, addr string) string { 47 return fmt.Sprintf(fileNameTemplate, os.Getpid(), proto, addr) 48 } 49 50 // Listen function is an alias for NewReusablePortListener. 51 func Listen(proto, addr string) (l net.Listener, err error) { 52 return NewReusablePortListener(proto, addr) 53 } 54 55 // ListenPacket is an alias for NewReusablePortPacketConn. 56 func ListenPacket(proto, addr string) (l net.PacketConn, err error) { 57 return NewReusablePortPacketConn(proto, addr) 58 }