From bac7bb61df310a7210c6e1fc2ddf0f6fe8a78697 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E7=A5=A5=E8=B6=85?= Date: Thu, 3 Dec 2020 11:23:29 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E8=8E=B7=E5=8F=96=E9=9A=8F?= =?UTF-8?q?=E6=9C=BA=E7=AB=AF=E5=8F=A3=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/nodeconfigs/toa_config.go | 8 +++++++- pkg/nodeconfigs/toa_config_test.go | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/pkg/nodeconfigs/toa_config.go b/pkg/nodeconfigs/toa_config.go index 65afe34..0e00f5f 100644 --- a/pkg/nodeconfigs/toa_config.go +++ b/pkg/nodeconfigs/toa_config.go @@ -3,6 +3,7 @@ package nodeconfigs import ( "fmt" "github.com/iwind/TeaGo/rands" + "net" ) // 默认的TOA配置 @@ -68,7 +69,12 @@ func (this *TOAConfig) SockFile() string { // 获取随机端口 func (this *TOAConfig) RandLocalPort() uint16 { - return uint16(rands.Int(this.minLocalPort, this.maxLocalPort)) + listener, err := net.Listen("tcp", ":0") + if err != nil { + return uint16(rands.Int(this.minLocalPort, this.maxLocalPort)) + } + _ = listener.Close() + return uint16(listener.Addr().(*net.TCPAddr).Port) } // 转换为参数的形式 diff --git a/pkg/nodeconfigs/toa_config_test.go b/pkg/nodeconfigs/toa_config_test.go index 1aef6bb..bcc57d9 100644 --- a/pkg/nodeconfigs/toa_config_test.go +++ b/pkg/nodeconfigs/toa_config_test.go @@ -1,8 +1,10 @@ package nodeconfigs import ( + "net" "runtime" "testing" + "time" ) func TestTOAConfig_RandLocalPort(t *testing.T) { @@ -27,6 +29,19 @@ func TestTOAConfig_RandLocalPort(t *testing.T) { } } +func TestTOAConfig_FreePort(t *testing.T) { + before := time.Now() + listener, err := net.Listen("tcp", ":0") + if err != nil { + t.Fatal(err) + } + t.Log(listener.Addr()) + _ = listener.Close() + t.Log(time.Since(before).Seconds()*1000, "ms") + time.Sleep(30 * time.Second) +} + + func TestTOAConfig_AsArgs(t *testing.T) { toa := &TOAConfig{ IsOn: false,