增加tcping的兼容性处理代码

This commit is contained in:
dushixiang
2021-03-21 10:28:54 +08:00
parent 2739279448
commit d6e227bc93
2 changed files with 19 additions and 5 deletions

View File

@ -22,7 +22,14 @@ func TestTcping(t *testing.T) {
ip6res := utils.Tcping(localhost6, 9999)
assert.Equal(t, true, ip6res)
ip4resWithBracket := utils.Tcping("["+localhost4+"]", 9999)
assert.Equal(t, true, ip4resWithBracket)
ip6resWithBracket := utils.Tcping("["+localhost6+"]", 9999)
assert.Equal(t, true, ip6resWithBracket)
defer func() {
conn.Close()
_ = conn.Close()
}()
}

View File

@ -85,13 +85,20 @@ func Tcping(ip string, port int) bool {
var (
conn net.Conn
err error
address string
)
strPort := strconv.Itoa(port)
if conn, err = net.DialTimeout("tcp", fmt.Sprintf("[%s]:%s", ip, strPort), 2*time.Second); err != nil {
if strings.HasPrefix(ip, "[") && strings.HasSuffix(ip, "]") {
// 如果用户有填写中括号就不再拼接
address = fmt.Sprintf("%s:%s", ip, strPort)
} else {
address = fmt.Sprintf("[%s]:%s", ip, strPort)
}
if conn, err = net.DialTimeout("tcp", address, 2*time.Second); err != nil {
return false
}
defer func() {
conn.Close()
_ = conn.Close()
}()
return true
}