github.com/sentienttechnologies/studio-go-runner@v0.0.0-20201118202441-6d21f2ced8ee/internal/runner/networking.go (about) 1 // Copyright 2018-2020 (c) Cognizant Digital Business, Evolutionary AI. All rights reserved. Issued under the Apache 2.0 License. 2 3 package runner 4 5 import ( 6 "net" 7 8 "github.com/go-stack/stack" 9 "github.com/jjeffery/kv" // MIT License 10 ) 11 12 // Functions related to networking needs for the runner 13 14 // GetFreePort will find and return a port number that is found to be available 15 // 16 func GetFreePort(hint string) (port int, err kv.Error) { 17 addr, errGo := net.ResolveTCPAddr("tcp", hint) 18 if errGo != nil { 19 return 0, kv.Wrap(errGo).With("stack", stack.Trace().TrimRuntime()) 20 } 21 22 l, errGo := net.ListenTCP("tcp", addr) 23 if errGo != nil { 24 return 0, kv.Wrap(errGo).With("stack", stack.Trace().TrimRuntime()) 25 } 26 27 port = l.Addr().(*net.TCPAddr).Port 28 29 // Dont defer as the port will be quickly reused 30 l.Close() 31 32 return port, nil 33 }