github.com/xraypb/xray-core@v1.6.6/testing/servers/udp/port.go (about)

     1  package udp
     2  
     3  import (
     4  	"github.com/xraypb/xray-core/common"
     5  	"github.com/xraypb/xray-core/common/net"
     6  )
     7  
     8  // PickPort returns an unused UDP port in the system. The port returned is highly likely to be unused, but not guaranteed.
     9  func PickPort() net.Port {
    10  	conn, err := net.ListenUDP("udp4", &net.UDPAddr{
    11  		IP:   net.LocalHostIP.IP(),
    12  		Port: 0,
    13  	})
    14  	common.Must(err)
    15  	defer conn.Close()
    16  
    17  	addr := conn.LocalAddr().(*net.UDPAddr)
    18  	return net.Port(addr.Port)
    19  }