add GetFreePort/GetFreePorts for package gipv4

This commit is contained in:
John Guo 2022-01-22 15:12:58 +08:00
parent 65d1648c30
commit 9e3a49dd1b
2 changed files with 61 additions and 1 deletions

View File

@ -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
}

View File

@ -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 <nil>
}
func ExampleGetFreePorts() {
fmt.Println(gipv4.GetFreePorts(2))
// Output:
// [57743 57744] <nil>
}