Daniele Rossi | d68b0b7 | 2019-10-31 11:36:05 +0100 | [diff] [blame] | 1 | package freeport |
| 2 | |
| 3 | import ( |
| 4 | "net" |
| 5 | ) |
| 6 | |
| 7 | // GetFreePort asks the kernel for a free open port that is ready to use. |
| 8 | func GetFreePort() (int, error) { |
| 9 | addr, err := net.ResolveTCPAddr("tcp", "localhost:0") |
| 10 | if err != nil { |
| 11 | return 0, err |
| 12 | } |
| 13 | |
| 14 | l, err := net.ListenTCP("tcp", addr) |
| 15 | if err != nil { |
| 16 | return 0, err |
| 17 | } |
| 18 | defer l.Close() |
| 19 | return l.Addr().(*net.TCPAddr).Port, nil |
| 20 | } |
| 21 | |
| 22 | // GetPort is deprecated, use GetFreePort instead |
| 23 | // Ask the kernel for a free open port that is ready to use |
| 24 | func GetPort() int { |
| 25 | port, err := GetFreePort() |
| 26 | if err != nil { |
| 27 | panic(err) |
| 28 | } |
| 29 | return port |
| 30 | } |
| 31 | |
| 32 | // GetFreePort asks the kernel for free open ports that are ready to use. |
| 33 | func GetFreePorts(count int) ([]int, error) { |
| 34 | var ports []int |
| 35 | for i := 0; i < count; i++ { |
| 36 | addr, err := net.ResolveTCPAddr("tcp", "localhost:0") |
| 37 | if err != nil { |
| 38 | return nil, err |
| 39 | } |
| 40 | |
| 41 | l, err := net.ListenTCP("tcp", addr) |
| 42 | if err != nil { |
| 43 | return nil, err |
| 44 | } |
| 45 | defer l.Close() |
| 46 | ports = append(ports, l.Addr().(*net.TCPAddr).Port) |
| 47 | } |
| 48 | return ports, nil |
| 49 | } |