-
Notifications
You must be signed in to change notification settings - Fork 67
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Syrone Wong <[email protected]>
- Loading branch information
1 parent
ed9a135
commit c379ab8
Showing
2 changed files
with
44 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
// Taken from https://github.com/phayes/freeport | ||
package freeport | ||
|
||
import ( | ||
"net" | ||
) | ||
|
||
// GetFreePort asks the kernel for a free open port that is ready to use. | ||
func GetFreePort() (int, error) { | ||
addr, err := net.ResolveTCPAddr("tcp", "localhost:0") | ||
if err != nil { | ||
return 0, err | ||
} | ||
|
||
l, err := net.ListenTCP("tcp", addr) | ||
if err != nil { | ||
return 0, err | ||
} | ||
defer l.Close() | ||
return l.Addr().(*net.TCPAddr).Port, nil | ||
} | ||
|
||
// GetFreePort asks the kernel for free open ports that are ready to use. | ||
func GetFreePorts(count int) ([]int, error) { | ||
var ports []int | ||
for i := 0; i < count; i++ { | ||
addr, err := net.ResolveTCPAddr("tcp", "localhost:0") | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
l, err := net.ListenTCP("tcp", addr) | ||
if err != nil { | ||
return nil, err | ||
} | ||
defer l.Close() | ||
ports = append(ports, l.Addr().(*net.TCPAddr).Port) | ||
} | ||
return ports, nil | ||
} |