github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/testing/servers/udp/port.go (about)

     1  package udp
     2  
     3  import "github.com/v2fly/v2ray-core/v5/common/net"
     4  
     5  // PickPort returns an unused UDP port of the system.
     6  func PickPort() net.Port {
     7  	conn := pickPort()
     8  	defer conn.Close()
     9  
    10  	addr := conn.LocalAddr().(*net.UDPAddr)
    11  	return net.Port(addr.Port)
    12  }
    13  
    14  func pickPort() *net.UDPConn {
    15  	conn, err := net.ListenUDP("udp4", &net.UDPAddr{
    16  		IP:   net.LocalHostIP.IP(),
    17  		Port: 0,
    18  	})
    19  	if err != nil {
    20  		conn = pickPort()
    21  	}
    22  	return conn
    23  }