1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2025-01-02 15:36:41 -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 package tcp
import ( import "v2ray.com/core/common/net"
"v2ray.com/core/common"
"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 { func PickPort() net.Port {
listener, err := net.Listen("tcp4", "127.0.0.1:0") listener := pickPort()
common.Must(err)
defer listener.Close() defer listener.Close()
addr := listener.Addr().(*net.TCPAddr) addr := listener.Addr().(*net.TCPAddr)
return net.Port(addr.Port) 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 package udp
import ( import "v2ray.com/core/common/net"
"v2ray.com/core/common"
"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 { func PickPort() net.Port {
conn, err := net.ListenUDP("udp4", &net.UDPAddr{ conn := pickPort()
IP: net.LocalHostIP.IP(),
Port: 0,
})
common.Must(err)
defer conn.Close() defer conn.Close()
addr := conn.LocalAddr().(*net.UDPAddr) addr := conn.LocalAddr().(*net.UDPAddr)
return net.Port(addr.Port) 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
}