This repository has been archived by the owner on Jul 18, 2018. It is now read-only.
/
netutils.go
82 lines (69 loc) · 1.58 KB
/
netutils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package util
import (
"errors"
log "github.com/cihub/seelog"
"net"
"strconv"
"strings"
)
func TestPort(port int) bool {
host := ":" + strconv.Itoa(port)
ln, err := net.Listen("tcp", host)
if err != nil {
log.Debugf("can't listen on port %s, %s", host, err)
return false
}
ln.Close()
return true
}
func TestListenPort(ip string, port int) bool {
log.Tracef("testing port %s:%d", ip, port)
host := ip + ":" + strconv.Itoa(port)
ln, err := net.Listen("tcp", host)
if err != nil {
log.Debugf("can't listen on port %s, %s", host, err)
return false
}
ln.Close()
return true
}
/**
get valid port to listen, if the specify port is not available, auto choose the next one
*/
func GetAvailablePort(ip string, port int) int {
maxRetry := 500
for i := 0; i < maxRetry; i++ {
ok := TestListenPort(ip, port)
if ok {
return port
}
port++
}
panic(errors.New("no ports available"))
}
/**
get valid address to listen, if the specify port is not available, auto choose the next one
*/
func AutoGetAddress(addr string) string {
if strings.Index(addr, ":") < 0 {
panic(errors.New("invalid address, eg ip:port, " + addr))
}
array := strings.Split(addr, ":")
p, _ := strconv.Atoi(array[1])
port := GetAvailablePort(array[0], p)
array[1] = strconv.Itoa(port)
return strings.Join(array, ":")
}
/**
get valid address, input: :8001 -> output: 127.0.0.1:8001
*/
func GetValidAddress(addr string) string {
if strings.Index(addr, ":") >= 0 {
array := strings.Split(addr, ":")
if len(array[0]) == 0 {
array[0] = "127.0.0.1"
addr = strings.Join(array, ":")
}
}
return addr
}