github.com/sereiner/library@v0.0.0-20200518095232-1fa3e640cc5f/net/net.go (about) 1 package net 2 3 import ( 4 "fmt" 5 "math/rand" 6 "net" 7 "strings" 8 "time" 9 ) 10 11 const ( 12 minTCPPort = 0 13 maxTCPPort = 65535 14 maxReservedTCPPort = 1024 15 maxRandTCPPort = maxTCPPort - (maxReservedTCPPort + 1) 16 ) 17 18 var ( 19 tcpPortRand = rand.New(rand.NewSource(time.Now().UnixNano())) 20 ) 21 22 // IsTCPPortAvailable returns a flag indicating whether or not a TCP port is 23 // available. 24 func IsTCPPortAvailable(port int) bool { 25 conn, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) 26 if err != nil { 27 return false 28 } 29 conn.Close() 30 return true 31 } 32 33 // RandomTCPPort gets a free, random TCP port between 1025-65535. If no free 34 // ports are available -1 is returned. 35 func RandomTCPPort() int { 36 for i := maxReservedTCPPort; i < maxTCPPort; i++ { 37 p := tcpPortRand.Intn(maxRandTCPPort) + maxReservedTCPPort + 1 38 if IsTCPPortAvailable(p) { 39 return p 40 } 41 } 42 return -1 43 } 44 45 //GetAvailablePort 获取可用的端口号 46 func GetAvailablePort(ports []int) int { 47 for i := 0; i < len(ports); i++ { 48 if IsTCPPortAvailable(ports[i]) { 49 return ports[i] 50 } 51 } 52 return -1 53 } 54 55 // GetLocalIPAddress 获取IP地址 56 func GetLocalIPAddress(masks ...string) string { 57 addrs, err := net.InterfaceAddrs() 58 if err != nil { 59 return "127.0.0.1" 60 } 61 var ipLst []string 62 for _, addr := range addrs { 63 if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil { 64 ipLst = append(ipLst, ipnet.IP.String()) 65 } 66 } 67 if len(masks) == 0 && len(ipLst) > 0 { 68 return ipLst[0] 69 } 70 for _, ip := range ipLst { 71 for _, m := range masks { 72 if strings.HasPrefix(ip, m) { 73 return ip 74 } 75 } 76 } 77 return "127.0.0.1" 78 }