github.com/songzhibin97/gkit@v1.2.13/net/port/port.go (about)

     1  package port
     2  
     3  import "net"
     4  
     5  func GetLocalFreePort() (int, error) {
     6  	addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
     7  	if err != nil {
     8  		return 0, err
     9  	}
    10  
    11  	l, err := net.ListenTCP("tcp", addr)
    12  	if err != nil {
    13  		return 0, err
    14  	}
    15  	defer l.Close()
    16  	return l.Addr().(*net.TCPAddr).Port, nil
    17  }