github.com/bazelbuild/rules_webtesting@v0.2.0/go/portpicker/port_picker.go (about) 1 // Copyright 2016 Google Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package portpicker provides methods for picking unused TCP ports. 16 package portpicker 17 18 import ( 19 "errors" 20 "io" 21 "net" 22 "strconv" 23 ) 24 25 var claimedPorts = map[int]bool{} 26 27 // PickUnusedPort picks an unused TCP port. 28 func PickUnusedPort() (int, error) { 29 var listeners []io.Closer 30 defer func() { 31 for _, c := range listeners { 32 c.Close() 33 } 34 }() 35 36 for i := 0; i <= len(claimedPorts); i++ { 37 l, err := net.Listen("tcp", ":0") 38 if err != nil { 39 return 0, err 40 } 41 listeners = append(listeners, l) 42 43 _, p, err := net.SplitHostPort(l.Addr().String()) 44 if err != nil { 45 return 0, err 46 } 47 48 port, err := strconv.Atoi(p) 49 if err != nil { 50 return 0, err 51 } 52 53 if !claimedPorts[port] { 54 claimedPorts[port] = true 55 return port, nil 56 } 57 } 58 return 0, errors.New("unable to get a port") 59 }