package network import ( "crypto/rand" "math/big" "net" "strconv" ) /** 扫描本机空闲端口 参数说明: startPort 扫描开始端口 不包含这个端口 endPort 扫描结束端口 不包含这个端口 count 扫描端口数量 */ func ScanPort(startPort, endPort int64, count int) []int64 { usePort := make([]int64, 0) for startPort < endPort { startPort = startPort + 1 udpserver, err := net.ResolveUDPAddr("udp", ":"+strconv.FormatInt(int64(startPort), 10)) if err != nil { continue } udpConn, err := net.ListenUDP("udp", udpserver) if err != nil { continue } udpConn.Close() ln, err := net.Listen("tcp", "0.0.0.0:"+strconv.FormatInt(int64(startPort), 10)) if err != nil { continue } usePort = append(usePort, startPort) ln.Close() if len(usePort) >= count { break } } return usePort } /** * 取随机端口 */ func RandPort(min, max int64) int64 { var port int64 for { port = RandInt64(min, max) udpserver, err := net.ResolveUDPAddr("udp", ":"+strconv.FormatInt(int64(port), 10)) if err != nil { continue } udpConn, err := net.ListenUDP("udp", udpserver) if err != nil { continue } udpConn.Close() ln, err := net.Listen("tcp", "0.0.0.0:"+strconv.FormatInt(int64(port), 10)) if err != nil { continue } ln.Close() break } return port } /** * 取随机数 */ func RandInt64(min, max int64) int64 { var randnum int64 for { maxBigInt := big.NewInt(max) i, _ := rand.Int(rand.Reader, maxBigInt) if i.Int64() > min { randnum = i.Int64() break } } return randnum }