1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-21 09:36:34 -05:00

Refine pick port logic (#481)

This commit is contained in:
Loyalsoldier 2020-12-02 23:48:32 +08:00 committed by GitHub
parent ff09993c8b
commit 45aeaa8080
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 17 deletions

View File

@ -1,16 +1,20 @@
package tcp
import (
"v2ray.com/core/common"
"v2ray.com/core/common/net"
)
import "v2ray.com/core/common/net"
// PickPort returns an unused TCP port in the system. The port returned is highly likely to be unused, but not guaranteed.
// PickPort returns an unused TCP port of the system.
func PickPort() net.Port {
listener, err := net.Listen("tcp4", "127.0.0.1:0")
common.Must(err)
listener := pickPort()
defer listener.Close()
addr := listener.Addr().(*net.TCPAddr)
return net.Port(addr.Port)
}
func pickPort() net.Listener {
listener, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
listener = pickPort()
}
return listener
}

View File

@ -1,19 +1,23 @@
package udp
import (
"v2ray.com/core/common"
"v2ray.com/core/common/net"
)
import "v2ray.com/core/common/net"
// PickPort returns an unused UDP port in the system. The port returned is highly likely to be unused, but not guaranteed.
// PickPort returns an unused UDP port of the system.
func PickPort() net.Port {
conn, err := net.ListenUDP("udp4", &net.UDPAddr{
IP: net.LocalHostIP.IP(),
Port: 0,
})
common.Must(err)
conn := pickPort()
defer conn.Close()
addr := conn.LocalAddr().(*net.UDPAddr)
return net.Port(addr.Port)
}
func pickPort() *net.UDPConn {
conn, err := net.ListenUDP("udp4", &net.UDPAddr{
IP: net.LocalHostIP.IP(),
Port: 0,
})
if err != nil {
conn = pickPort()
}
return conn
}