41 lines
851 B
Go
41 lines
851 B
Go
|
package utils
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"git.hpds.cc/Component/network/log"
|
||
|
"net"
|
||
|
)
|
||
|
|
||
|
// GetAvailablePort 获取可用端口
|
||
|
func GetAvailablePort() (int, error) {
|
||
|
address, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:0", "0.0.0.0"))
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
listener, err := net.ListenTCP("tcp", address)
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
defer func(listener *net.TCPListener) {
|
||
|
_ = listener.Close()
|
||
|
}(listener)
|
||
|
return listener.Addr().(*net.TCPAddr).Port, nil
|
||
|
}
|
||
|
|
||
|
// IsPortAvailable 判断端口是否可以(未被占用)
|
||
|
func IsPortAvailable(port int) bool {
|
||
|
address := fmt.Sprintf("%s:%d", "0.0.0.0", port)
|
||
|
listener, err := net.Listen("tcp", address)
|
||
|
if err != nil {
|
||
|
log.Infof("port %s is taken: %s", address, err)
|
||
|
return false
|
||
|
}
|
||
|
|
||
|
defer func(listener net.Listener) {
|
||
|
_ = listener.Close()
|
||
|
}(listener)
|
||
|
return true
|
||
|
}
|