github.com/sandwich-go/boost@v1.3.29/xip/free.go (about)

     1  package xip
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/sandwich-go/boost/internal/log"
     6  	"net"
     7  )
     8  
     9  // GetFreePort asks the kernel for a free open port that is ready to use.
    10  func GetFreePort() (int, error) {
    11  	addr, err0 := net.ResolveTCPAddr("tcp", "localhost:0")
    12  	if err0 != nil {
    13  		return 0, err0
    14  	}
    15  	l, err1 := net.ListenTCP("tcp", addr)
    16  	if err1 != nil {
    17  		return 0, err1
    18  	}
    19  	freePort := l.Addr().(*net.TCPAddr).Port
    20  	if err2 := l.Close(); err2 != nil {
    21  		log.Error(fmt.Sprintf("close free port: %d, err: %s", freePort, err2.Error()))
    22  	}
    23  	return freePort, nil
    24  }