blob: fcfb6bab0363e301562201094d04ea31c8dd5015 [file] [log] [blame]
Daniele Rossi17007a42019-10-17 16:21:52 +02001package freeport
2
3import (
4 "net"
5)
6
7// GetFreePort asks the kernel for a free open port that is ready to use.
8func 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
24func 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.
33func 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}