From 9e3a49dd1b23808fa0142a4202e7c2ea84a78f42 Mon Sep 17 00:00:00 2001 From: John Guo Date: Sat, 22 Jan 2022 15:12:58 +0800 Subject: [PATCH] add GetFreePort/GetFreePorts for package gipv4 --- net/gipv4/gipv4.go | 35 ++++++++++++++++++++++++++++++- net/gipv4/gipv4_z_example_test.go | 27 ++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 net/gipv4/gipv4_z_example_test.go diff --git a/net/gipv4/gipv4.go b/net/gipv4/gipv4.go index 0f38f65aa..d0902abb1 100644 --- a/net/gipv4/gipv4.go +++ b/net/gipv4/gipv4.go @@ -11,9 +11,10 @@ package gipv4 import ( "encoding/binary" "fmt" - "github.com/gogf/gf/v2/text/gregex" "net" "strconv" + + "github.com/gogf/gf/v2/text/gregex" ) // Ip2long converts ip address to an uint32 integer. @@ -57,3 +58,35 @@ func GetSegment(ip string) string { } return fmt.Sprintf("%s.%s.%s", match[1], match[2], match[3]) } + +// GetFreePort retrieves and returns a port that is free. +func GetFreePort() (port int, err error) { + addr, err := net.ResolveTCPAddr("tcp", ":0") + if err != nil { + return 0, err + } + l, err := net.ListenTCP("tcp", addr) + if err != nil { + return 0, err + } + port = l.Addr().(*net.TCPAddr).Port + _ = l.Close() + return +} + +// GetFreePorts retrieves and returns specified number of ports that are free. +func GetFreePorts(count int) (ports []int, err error) { + for i := 0; i < count; i++ { + addr, err := net.ResolveTCPAddr("tcp", ":0") + if err != nil { + return nil, err + } + l, err := net.ListenTCP("tcp", addr) + if err != nil { + return nil, err + } + ports = append(ports, l.Addr().(*net.TCPAddr).Port) + _ = l.Close() + } + return ports, nil +} diff --git a/net/gipv4/gipv4_z_example_test.go b/net/gipv4/gipv4_z_example_test.go new file mode 100644 index 000000000..10a6dcfb4 --- /dev/null +++ b/net/gipv4/gipv4_z_example_test.go @@ -0,0 +1,27 @@ +// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package gipv4_test + +import ( + "fmt" + + "github.com/gogf/gf/v2/net/gipv4" +) + +func ExampleGetFreePort() { + fmt.Println(gipv4.GetFreePort()) + + // May Output: + // 57429 +} + +func ExampleGetFreePorts() { + fmt.Println(gipv4.GetFreePorts(2)) + + // Output: + // [57743 57744] +}