Skip to content

Commit

Permalink
maj:port: doc, parametrization, liting
Browse files Browse the repository at this point in the history
  • Loading branch information
burgesQ committed Apr 28, 2023
1 parent a98d9a4 commit dbe1d51
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions port/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,33 @@ package port

import (
"errors"
"fmt"
"net"
)

var ErrGetTCP = errors.New("get tcp address")
var (
ErrGetTCP = errors.New("get tcp address")
ErrNotIP = errors.New("provided value isn't a valid ip")
)

// GetFree return an available free port to listen on.
// It use the synthax 'localhost:0' under the hood to attempt to listen on a
// random port. The list ip, which default to localhost, can be parametrized.
func GetFree(ip ...string) (port int, err error) {
var (
a *net.TCPAddr
lip = "localhost"
)

func GetFree() (port int, err error) {
var a *net.TCPAddr
if len(ip) > 0 {
if net.ParseIP(ip[0]) == nil {
return 0, fmt.Errorf("%q: %w", ip[0], ErrNotIP)
}

lip = ip[0]
}

if a, err = net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {
if a, err = net.ResolveTCPAddr("tcp", lip+":0"); err == nil {
var l *net.TCPListener
if l, err = net.ListenTCP("tcp", a); err == nil {
defer l.Close()
Expand Down

0 comments on commit dbe1d51

Please sign in to comment.