Serge Bazanski | 549b72b | 2021-01-07 14:54:19 +0100 | [diff] [blame] | 1 | // Copyright 2020 The Monogon Project Authors. |
| 2 | // |
| 3 | // SPDX-License-Identifier: Apache-2.0 |
| 4 | // |
| 5 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | // you may not use this file except in compliance with the License. |
| 7 | // You may obtain a copy of the License at |
| 8 | // |
| 9 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | // |
| 11 | // Unless required by applicable law or agreed to in writing, software |
| 12 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | // See the License for the specific language governing permissions and |
| 15 | // limitations under the License. |
| 16 | |
| 17 | package freeport |
| 18 | |
| 19 | import ( |
| 20 | "io" |
| 21 | "net" |
| 22 | ) |
| 23 | |
| 24 | // AllocateTCPPort allocates a TCP port on the looopback address, and starts a temporary listener on it. That listener |
| 25 | // is returned to the caller alongside with the allocated port number. The listener must be closed right before |
| 26 | // the port is used by the caller. This naturally still leaves a race condition window where that port number |
| 27 | // might be snatched up by some other process, but there doesn't seem to be a better way to do this. |
| 28 | func AllocateTCPPort() (uint16, io.Closer, error) { |
| 29 | addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0") |
| 30 | if err != nil { |
| 31 | return 0, nil, err |
| 32 | } |
| 33 | |
| 34 | l, err := net.ListenTCP("tcp", addr) |
| 35 | if err != nil { |
| 36 | return 0, nil, err |
| 37 | } |
| 38 | return uint16(l.Addr().(*net.TCPAddr).Port), l, nil |
| 39 | } |
| 40 | |
| 41 | // MustConsume takes the result of AllocateTCPPort, closes the listener and returns the allocated port. |
| 42 | // If anything goes wrong (port could not be allocated or closed) it will panic. |
| 43 | func MustConsume(port uint16, lis io.Closer, err error) int { |
| 44 | if err != nil { |
| 45 | panic(err) |
| 46 | } |
| 47 | if err := lis.Close(); err != nil { |
| 48 | panic(err) |
| 49 | } |
| 50 | return int(port) |
| 51 | } |