github.com/projecteru2/core@v0.0.0-20240321043226-06bcc1c23f58/utils/service.go (about) 1 package utils 2 3 import ( 4 "fmt" 5 "net" 6 "strings" 7 8 "github.com/cockroachdb/errors" 9 "github.com/projecteru2/core/types" 10 ) 11 12 // GetOutboundAddress finds out self-service address 13 func GetOutboundAddress(bind string, probeTarget string) (string, error) { 14 parts := strings.Split(bind, ":") 15 if len(parts) != 2 { 16 return "", errors.Wrap(types.ErrInvaildIPWithPort, bind) 17 } 18 ip := parts[0] 19 port := parts[1] 20 21 address := net.ParseIP(ip) 22 if ip == "" || address == nil || address.IsUnspecified() { 23 return getOutboundAddress(port, probeTarget) 24 } 25 26 return bind, nil 27 } 28 29 func getOutboundAddress(port string, probeTarget string) (string, error) { 30 conn, err := net.Dial("udp", probeTarget) 31 if err != nil { 32 return "", err 33 } 34 defer conn.Close() 35 36 localAddr := conn.LocalAddr().(*net.UDPAddr) 37 return fmt.Sprintf("%s:%s", localAddr.IP, port), nil 38 }